Flutter+Firebase中try/catch无报错输出的问题求助
问题描述
我参照YouTube教程写了Flutter登录页面,集成Firebase Auth实现邮箱密码登录。输入错误邮箱或密码时,try/catch块里的控制台打印(比如'wrong user')和错误弹窗都没触发,只会一直显示加载转圈;输入正确账号就能正常跳转到主页。我用的是VSCode+Pixel_3a_API_xx_x86安卓x64模拟器,试过无调试运行和flutter run命令都没用,求排查原因。
相关代码
final emailController = TextEditingController(); final passwordController = TextEditingController(); void signIn() async{ // loading circle print("SignIn"); showDialog( context: context, builder: (context) { return const Center( child: CircularProgressIndicator(), ); }, ); // dealing with incorrect email or password try { await FirebaseAuth.instance.signInWithEmailAndPassword( email: emailController.text, password: passwordController.text, ); // topmost component stacked will be popped (opposite of push) Navigator.pop(context); } on FirebaseAuthException catch (e) { Navigator.pop(context); if (e.code == 'user-not-found'){ print('wrong user'); wrongEmailMessage(); } else if (e.code == 'wrong-password'){ print('wrong pass'); wrongPassMessage(); } } } void wrongEmailMessage() { showDialog( context: context, builder: (context) { return const AlertDialog( backgroundColor: Colors.deepPurple, title: Center( child: Text('Incorrect Email', style: TextStyle(color: Colors.white),), ), ); }); }
问题原因及解决办法
上下文不匹配导致弹窗无法关闭
调用showDialog用的是当前页面context,但异步操作后,这个context可能无法正确指向加载弹窗,导致Navigator.pop(context)无法关闭弹窗,后续错误代码无法执行。
解决:改用Navigator.of(context, rootNavigator: true).pop()确保关闭最顶层弹窗,修改后的catch块及成功登录后的弹窗关闭代码:try { await FirebaseAuth.instance.signInWithEmailAndPassword( email: emailController.text, password: passwordController.text, ); Navigator.of(context, rootNavigator: true).pop(); } on FirebaseAuthException catch (e) { Navigator.of(context, rootNavigator: true).pop(); if (e.code == 'user-not-found'){ print('wrong user'); wrongEmailMessage(); } else if (e.code == 'wrong-password'){ print('wrong pass'); wrongPassMessage(); } }异常捕获范围不全
仅捕获FirebaseAuthException,但网络异常、初始化异常等其他错误会导致代码卡住,加载弹窗持续显示。
解决:添加通用异常捕获:try { // 原有登录逻辑 } on FirebaseAuthException catch (e) { // 原有Firebase错误处理 } catch (e) { Navigator.of(context, rootNavigator: true).pop(); print('其他错误:$e'); // 可添加通用错误提示弹窗 }Firebase初始化未完成
若main函数未完成Firebase初始化,Auth操作会卡住,无法抛出异常。
解决:确保main函数里完成初始化:void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(const MyApp()); }模拟器网络问题
安卓模拟器可能存在网络连接故障,导致Firebase请求无法返回。
解决:重启模拟器、检查模拟器网络是否能访问外网,或切换真机测试。
内容的提问来源于stack exchange,提问作者Hal03
相关产品推荐
相关产品推荐

