Firebase邮箱登录触发PlatformException无效凭证问题求助
问题描述
测试Flutter应用的邮箱登录功能时,使用无效邮箱登录会触发以下异常:
PlatformException(ERROR_INVALID_CREDENTIAL, The supplied auth credential is incorrect, malformed or has expired., {}, null)
已在LoginCubit中处理该异常,且将firebase_auth和firebase_core更新至最新版本,但问题仍未解决。
相关代码如下:
LoginCubit代码
Future<void> loginWithEmail(String email, String password) async { emit(LoginLoading()); try { UserCredential userCredential = await _authService.signInWithEmailAndPassword(email, password); emit(LoginSuccess(userCredential.user!)); } on FirebaseAuthException catch (e) { // Handle Firebase exceptions String errorMessage = _handleFirebaseAuthException(e); emit(LoginFailure(errorMessage)); } on PlatformException catch (e) { // Handle platform exceptions emit(LoginFailure(_handlePlatformException(e))); } catch (e) { // Handle other exceptions emit(LoginFailure("An unexpected error occurred")); } } String _handlePlatformException(PlatformException e) { // Handle specific platform exceptions // The error handling here depends on the specific exceptions you expect // For instance, handling Google Sign-In or Apple Sign-In errors switch (e.code) { case 'ERROR_GOOGLE_SIGN_IN_FAILED': return "Google sign-in failed. Please try again."; // ERROR_INVALID_CREDENTIAL case 'ERROR_INVALID_CREDENTIAL': return "Invalid Email Credentials."; // Add more cases as needed default: return "An error occurred on the platform side: ${e.message}"; } }
登录页面代码
body: BlocConsumer<LoginCubit, LoginState>( listener: (context, state) { if (state is LoginSuccess) { debugPrint('Login Is Succusseflly'); context.goNamed(AppRoutes.bottomNavBarRoute); } else if (state is LoginFailure) { showDialog( context: context, builder: (context) => AlertDialog( actions: [ TextButton( onPressed: () { Navigator.of(context).pop(); }, child: const Text('Close')) ], title: const Text('Alert'), icon: SvgPicture.asset('assets/alert.svg'), contentPadding: const EdgeInsets.all(20), content: Text(state.error), )); } }, builder: (context, state) { if (state is LoginLoading) { return const Center( child: CircularProgressIndicator(), ); } if (_formKey.currentState!.validate()) { final email = _emailController.text; final password = _passwordController.text; BlocProvider.of<LoginCubit>(context) .loginWithEmail(email, password); }
Firebase Auth服务代码
Future<UserCredential> signInWithEmailAndPassword( String email, String password) async { return await _firebaseAuth.signInWithEmailAndPassword( email: email, password: password); }
解决方案
1. 确认异常类型与错误码
先在异常捕获块中添加打印语句,明确实际抛出的异常类型和错误码:
} on FirebaseAuthException catch (e) { print('FirebaseAuthException: code=${e.code}, msg=${e.message}'); String errorMessage = _handleFirebaseAuthException(e); emit(LoginFailure(errorMessage)); } on PlatformException catch (e) { print('PlatformException: code=${e.code}, msg=${e.message}'); emit(LoginFailure(_handlePlatformException(e))); }
运行测试后查看控制台输出,确认异常来源和具体错误码。
2. 完善FirebaseAuthException处理逻辑
大概率是FirebaseAuthException未被正确处理,导致异常流转到PlatformException捕获块。补充_handleFirebaseAuthException方法,覆盖常见的邮箱登录错误码:
String _handleFirebaseAuthException(FirebaseAuthException e) { switch (e.code) { case 'invalid-email': return '邮箱格式无效,请检查输入'; case 'user-not-found': return '该邮箱未注册'; case 'wrong-password': return '密码错误'; case 'invalid-credential': return '无效的登录凭证'; default: return '登录失败:${e.message ?? '未知错误'}'; } }
3. 前端提前验证邮箱格式
在调用登录接口前,通过表单验证提前拦截无效邮箱格式,减少不必要的Firebase API调用:
TextFormField( controller: _emailController, validator: (value) { if (value == null || value.isEmpty) { return '请输入邮箱'; } final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$'); if (!emailRegex.hasMatch(value)) { return '请输入有效的邮箱地址'; } return null; }, )
4. 清理项目缓存并重新构建
执行以下命令清理缓存,避免旧版本依赖残留:
flutter clean flutter pub get
之后重启IDE和模拟器/真机,重新运行项目。
5. 核对FirebaseAuth错误码版本兼容性
新版本firebase_auth的错误码已改为小写格式(如invalid-credential而非ERROR_INVALID_CREDENTIAL),更新_handlePlatformException中的错误码匹配:
case 'invalid-credential': return '无效的邮箱凭证';
内容的提问来源于stack exchange,提问作者Mahmoud Shaaban
相关产品推荐
相关产品推荐

