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

Flutter Alert Dialog在Chrome调试时无法显示的问题求助

AlertDialog无法正常显示的问题修复

问题原因

你在PopupMenuItem的onTap方法中,先调用ShowMyDialog()后立刻执行Navigator.pop(context)。由于showDialog是异步操作,Navigator.pop会优先执行,直接关闭了弹出菜单所在的路由,导致AlertDialog依赖的上下文被销毁,最终对话框无法显示。

修复方案

方案一:等待对话框操作完成后再关闭菜单

修改PopupMenuItem的onTap逻辑,使用await等待对话框的异步操作完成,再执行Navigator.pop:

PopupMenuItem(
  value: 1,
  onTap: () async {
    await ShowMyDialog();
    Navigator.pop(context);
  },
  child: ListTile(
    leading: Icon(Icons.edit),
    title: Text("Edit"),
 ),
),

方案二:先关闭菜单,延迟显示对话框

如果希望先关闭弹出菜单,再显示对话框,可以使用WidgetsBinding.instance.addPostFrameCallback,确保菜单关闭后在下一帧渲染对话框:

PopupMenuItem(
  value: 1,
  onTap: () {
    Navigator.pop(context);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ShowMyDialog();
    });
  },
  child: ListTile(
    leading: Icon(Icons.edit),
    title: Text("Edit"),
 ),
),

说明

两种方案都能解决对话框不显示的问题:

  • 方案一适合需要用户完成对话框操作后再关闭菜单的场景;
  • 方案二适合先关闭菜单,再独立显示对话框的场景。

内容的提问来源于stack exchange,提问作者Muhammad Bilal Ijaz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 19:15:28