【问题标题】:Flutter error catch e.message not workingFlutter 错误捕获 e.message 不起作用
【发布时间】:2021-10-06 05:36:52
【问题描述】:
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);
    }
  }

错误:getter 'message' 没有为类 'Object' 定义。尝试 将名称更正为现有 getter 的名称,或定义一个 名为“消息”的 getter 或字段。

知道为什么它不起作用吗?

【问题讨论】:

  • 您为什么不尝试打印e 或添加一个断点来检查它包含什么?
  • 试试打印e的值看看是什么类型?
  • 它的类型是 FirebaseAuthException。打印它显示:[firebase_auth/invalid-email] 电子邮件地址格式错误。我想从输出中避免“[firebase_auth/invalid-email]”这个

标签: flutter dart flutter-getx


【解决方案1】:

原因是您捕获的e 对象没有message 属性。您可以使用print(e.runtimeType) 查看它是哪种类型。如果你想捕获某种特定类型的异常,你应该尝试:

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

【讨论】:

  • runtimeType 是 FirebaseAuthException 。
【解决方案2】:

通过在catch 之前添加on FirebaseAuthException 并将e.message 转换为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);
    }
  }

【讨论】:

    猜你喜欢
    • 2019-03-02
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    • 2015-02-11
    • 1970-01-01
    相关资源
    最近更新 更多