Flutter error catch e.message not working

Viewed 827
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?

3 Answers

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) {
   // 
}

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);
    }
  }

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

Related