You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 15:06:02