You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Firebase登录时user-not-found错误无法被try-catch捕获

问题解决:try-catch无法捕获Firebase Auth的user-not-found错误

核心问题是你没有等待异步操作完成,导致signInWithEmailAndPassword抛出的错误无法被try-catch捕获,同时print("UC = ")会被提前执行。

错误原因

FirebaseAuth.instance.signInWithEmailAndPassword()是异步方法,返回Future<UserCredential>。你当前的代码没有用await修饰这个调用,所以程序不会等待登录请求完成,直接执行后续的print语句;而异步操作抛出的错误会在后台变成未处理异常,根本进入不了try-catch块。

修正后的代码

TextButton(
  onPressed: () async {
    final email = _eMail.text;
    final password = _passWord.text;
    try {
      // 添加await等待异步操作完成
      final userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
        email: email,
        password: password,
      );
      print("UC = ");
      print(userCredential);
    } catch (e) {
      print("Error Code: ");
      print(e.runtimeType);
      print(e);
    }
  },
  child: Text("Login"),
),

修正后效果

添加await后,程序会等待登录请求执行完成:

  • 若登录成功,才会执行后续的print语句;
  • 若抛出user-not-found或其他错误,会被try-catch捕获,进入catch块打印错误信息,不会执行print("UC = ")。

内容的提问来源于stack exchange,提问作者Anshumaan Mishra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 19:40:00