'Flutter error catch e.message not working

void createUser(String email, String password) async {
    try {
      await _auth
          .createUserWithEmailAndPassword(email: email, password: password)
          .then((value) => Get.offAll(Home()));
    } catch (e) {
      Get.snackbar("Error while creating account", e.message, //Error on e.message
          snackPosition: SnackPosition.BOTTOM);
    }
  }

Error: The getter 'message' isn't defined for the class 'Object'. Try correcting the name to the name of an existing getter, or defining a getter or field named 'message'.

Any idea why it is not working?



Solution 1:[1]

The reason for this is the e object you are catching doesnt have the message property. You can see which type it is by using print(e.runtimeType). If you want to catch some specific type of Exception, you should try:

try {
   // 
} on SomeClass catch (e) {
    print(e.message)
} catch (e) {
   // 
}

Solution 2:[2]

Problem solved by adding on FirebaseAuthException before catch and converting e.message to e.message.tostring()

void createUser(String email, String password) async {
    try {
      await _auth
          .createUserWithEmailAndPassword(email: email, password: password)
          .then((value) => Get.offAll(Home()));
    } on FirebaseAuthException catch (e) {
      Get.snackbar("Error while creating account", e.message.toString(),
          snackPosition: SnackPosition.BOTTOM);
    }
  }

Solution 3:[3]

Problem solved by adding on FirebaseAuthException before catch and converting e.message to e.message.tostring().

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Luis Cárcamo
Solution 2 Akhil
Solution 3 Tyler2P