Flutter中Firebase响应后自动关闭加载对话框问题
解决方案
问题出在登录失败时未关闭之前弹出的加载对话框,导致它与错误对话框同时存在。只需在处理错误前先关闭加载对话框,同时优化登录成功后的流程即可解决。
修改后的登录方法代码
Future signIn()async{ try { // 弹出加载对话框,设置barrierDismissible防止用户误触关闭 showDialog( context: context, barrierDismissible: false, builder: (context) => const AlertDialog( title: Center( child: CircularProgressIndicator( color: Colors.deepOrange, ), ), ) ); await FirebaseAuth.instance.signInWithEmailAndPassword( email: emailController.text, password: passwordController.text, ); // 等待数据获取完成,确保role_firestore已赋值 await fetchData(); // 先关闭加载对话框,再跳转到对应页面 Navigator.pop(context); if (role_firestore == 'Admin'){ Navigator.push(context, MaterialPageRoute(builder: (context) => AdminHomePage())); }else if (role_firestore == 'User'){ Navigator.push(context, MaterialPageRoute(builder: (context) => MainPage())); }else if (role_firestore == 'Restaurant'){ Navigator.push(context, MaterialPageRoute(builder: (context) => Restaurants())); } } on FirebaseAuthException catch (e) { // 登录失败时先关闭加载对话框 Navigator.pop(context); final result = await Connectivity().checkConnectivity(); showConnectivitySnackBar(result); handleLoginError(e); } catch (e) { // 捕获其他未知异常,同样关闭加载对话框 Navigator.pop(context); showDialog( context: context, builder: (context)=> const AlertDialog( title: Text("错误",style: TextStyle(color: Colors.deepOrange)), content: Text("登录过程中出现未知错误"), actions: [ TextButton( onPressed: () {Navigator.of(context).pop();}, child: Text("Ok",style: TextStyle(color: Colors.deepOrange)), ) ], ) ); } }
关键修改点
- 登录失败时关闭加载对话框:在
catch块开头执行Navigator.pop(context),确保加载对话框被关闭后再弹出错误提示。 - 登录成功时先关对话框再跳转:避免加载对话框在页面跳转后残留。
- 添加
barrierDismissible: false:防止用户在认证过程中点击外部关闭加载对话框,保证流程完整性。 fetchData()添加await:确保角色数据获取完成后再进行页面跳转判断,避免逻辑错误。
错误对话框代码(保持原样即可)
showDialog( context: context, builder: (context)=> AlertDialog( title: const Text("Log In Failed",style: TextStyle(color: Colors.deepOrange)), content: Text(messageToDisplay,style: TextStyle(color: Colors.deepOrange)), actions: [ TextButton( onPressed: () {Navigator.of(context, rootNavigator: true).pop();}, child: const Text("Ok",style: TextStyle(color: Colors.deepOrange)), ) ], ) );
内容的提问来源于stack exchange,提问作者H. M. Zaheer Asghar
相关产品推荐
相关产品推荐

