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

Flutter Firebase登录时错误凭证未触发自定义SnackBar问题

问题解决方法

1. 适配Firebase Auth新版错误码逻辑

Firebase Auth 新版本已将user-not-found和wrong-password统一合并为INVALID_LOGIN_CREDENTIALS错误码,原代码中先判断旧码的逻辑会导致新错误无法触发对应SnackBar。调整异常捕获顺序,优先处理新错误码:

Future<void> signIn() async {
    try {
      if (emailController.text.trim().isEmpty) {
        return showWarningSnackBar(context, 'Empty Email');
      }
      if (passwordController.text.trim().isEmpty) {
        return showWarningSnackBar(context, 'Empty Password');
      }

      await AuthService().signInUser(
        emailController.text.trim(),
        passwordController.text.trim(),
      );
      if (!context.mounted) return;
      showSnackBar(context, 'Successfully logged in');
    } on FirebaseAuthException catch (e) {
      if (!context.mounted) return;
      if (e.code == 'INVALID_LOGIN_CREDENTIALS') {
        showErrorSnackBar(context, 'Login credentials are invalid.');
      } else if (e.code == 'invalid-email') {
        showErrorSnackBar(context, 'The email address is badly formatted.');
      } else {
        showErrorSnackBar(context, 'Login failed: ${e.message}');
      }
    } catch (e) {
      if (context.mounted) {
        showErrorSnackBar(context, 'An unexpected error occurred.');
      }
    }
  }

2. 可选:优化AuthService异常处理

若想减少控制台的原始错误日志输出,可在AuthService中捕获异常后重新抛出或处理:

Future<UserCredential?> signInUser(String email, String password) async {
  try {
    return await _auth.signInWithEmailAndPassword(
      email: email,
      password: password,
    );
  } on FirebaseAuthException catch (e) {
    rethrow; // 重新抛出以便上层处理
  } catch (e) {
    print('Sign in error: $e');
    return null;
  }
}

关键注意事项

  • 显示SnackBar前必须判断context.mounted,避免上下文已销毁引发的错误
  • 控制台输出的INVALID_LOGIN_CREDENTIALS日志是Firebase内部调试信息,不影响业务逻辑,无需强制屏蔽
  • 旧版的user-not-found和wrong-password错误码已不再使用,可从代码中移除对应判断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 05:13:18