如何在Flutter的catch代码块中正确调用AlertDialog处理登录错误
问题原因
你在catch代码块中仅创建了AlertDialog组件实例,没有调用Flutter官方提供的showDialog方法触发弹窗渲染,所以错误触发时页面没有任何反馈。
修正方案
替换catch代码块内容,补充showDialog调用逻辑,完整的onPressed代码如下:
onPressed: () async { try { final user = await _auth.signInWithEmailAndPassword( email: email!, password: password!); if (user != null) { var customerInfo = CustomerInfo(email: email); await customerInfo.getCustomerData(); // 防止页面销毁后跳转报错,可补充mounted判断 if (!mounted) return; Navigator.push( context, MaterialPageRoute( builder: (context) => CustomerScreen( customerInfo: customerInfo))); } } catch (e) { // 防止页面销毁后弹窗报错,补充mounted判断 if (!mounted) return; await showDialog( context: context, builder: (context) => AlertDialog( title: const Text("Warning!"), content: const Text("Email or Password is wrong!"), actions: [ ElevatedButton( onPressed: () { // 点击后关闭弹窗 Navigator.pop(context); }, child: const Text("Yes"), ), ], ), ); } },
关键说明
showDialog是Flutter内置的弹窗触发方法,必须传入当前页面的context参数才能正常渲染- 补充
mounted判断可以避免当前页面已被销毁时,调用弹窗/跳转方法抛出的上下文异常 - 弹窗的按钮点击事件中需要调用
Navigator.pop(context)关闭弹窗,否则弹窗会一直停留在页面上
内容的提问来源于stack exchange,提问作者themmfa
相关产品推荐
相关产品推荐

