Flutter Firebase登录输入错误凭证未抛出对应异常求助
解决Firebase登录错误提示不明确的问题
问题现状
输入错误邮箱或密码时,Firebase返回的是包含[firebase_auth/INVALID_LOGIN_CREDENTIALS]的内部错误栈,无法直接给用户展示“邮箱不存在”或“密码错误”的明确提示。
解决方案
Firebase Auth抛出的错误属于FirebaseAuthException类型,通过捕获该类型错误并判断其code字段,即可实现精准的错误提示:
修改后的登录代码
final _auth = FirebaseAuth.instance; Future<void> login() async { try { await _auth.signInWithEmailAndPassword( email: emailController.text, password: passwordController.text, ); // 注意:登录成功跳转到注册页面逻辑不合理,建议替换为主页/目标页面 Navigator.push( context, MaterialPageRoute( builder: (context) => HomeScreen(), // 替换为你的实际页面 ), ); } on FirebaseAuthException catch (error) { String errorMessage; switch (error.code) { case 'user-not-found': errorMessage = '该邮箱未注册'; break; case 'wrong-password': errorMessage = '密码错误'; break; case 'invalid-email': errorMessage = '邮箱格式无效'; break; case 'INVALID_LOGIN_CREDENTIALS': // 新版Firebase统一返回此code,可提示通用错误 errorMessage = '邮箱或密码错误'; break; default: errorMessage = '登录失败,请稍后重试'; debugPrint('登录错误详情:${error.code} - ${error.message}'); } utils().toastMessage(errorMessage); } catch (error, stackTrace) { // 处理非FirebaseAuth类型的未知错误 debugPrint('未知错误:$error'); utils().toastMessage('登录失败,请稍后重试'); } }
关键说明
- 优先捕获
FirebaseAuthException类型,避免全局捕获导致无法区分具体错误类型 - 依据Firebase官方定义的错误code,匹配对应友好提示文案
- 单独处理
INVALID_LOGIN_CREDENTIALS——这是新版Firebase针对无效登录凭证返回的统一code - 保留默认分支和全局catch,处理未预见的错误,同时后台打印详细错误便于调试
登录按钮代码(无需修改)
RoundButton( title: "Login", onTap: () { if (_formKey.currentState!.validate()) { login(); } }, ),
内容的提问来源于stack exchange,提问作者M.Shahzad
相关产品推荐
相关产品推荐

