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

Flutter中使用Navigator.pop无法关闭Loading弹窗求助

Flutter加载弹窗无法关闭的问题修复

你的代码问题在于:调用showDialog时使用的是当前页面的context,弹窗创建后会生成独立的上下文环境,后续的Navigator.pop(context)实际关闭的是当前页面而非弹窗,导致弹窗残留。

修复方案一:使用弹窗自身的上下文关闭

修改代码,保存弹窗的context,用它来关闭弹窗:

BuildContext? dialogContext;
// 显示加载弹窗
showDialog(
  context: context,
  barrierDismissible: false,
  builder: (BuildContext ctx) {
    dialogContext = ctx; // 保存弹窗的上下文
    return Dialog(
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: const [
          CircularProgressIndicator(),
          SizedBox(width: 16), // 添加间距优化布局
          Text("Loading"),
        ],
      ),
    );
  },
);

// 等待接口返回结果
instaprofile result = await getProfile(user.user!.username.toString());

// 关闭弹窗
if (dialogContext != null) {
  Navigator.pop(dialogContext!);
}

// 跳转新页面
Navigator.push(
  context,
  MaterialPageRoute(builder: (context) => ProfilePage(userbio: result)),
);

修复方案二:使用Root Navigator关闭

如果不需要精准控制弹窗上下文,可以直接通过Root Navigator关闭弹窗(showDialog默认将弹窗加入Root Navigator栈):

// 显示加载弹窗
showDialog(
  context: context,
  barrierDismissible: false,
  builder: (BuildContext ctx) {
    return Dialog(
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: const [
          CircularProgressIndicator(),
          SizedBox(width: 16),
          Text("Loading"),
        ],
      ),
    );
  },
);

// 等待接口返回结果
instaprofile result = await getProfile(user.user!.username.toString());

// 关闭弹窗
Navigator.of(context, rootNavigator: true).pop();

// 跳转新页面
Navigator.push(
  context,
  MaterialPageRoute(builder: (context) => ProfilePage(userbio: result)),
);

额外优化建议

  • 给CircularProgressIndicator和Text之间添加SizedBox,优化布局美观度
  • 给异步请求添加错误捕获,避免请求失败后弹窗一直残留:
try {
  instaprofile result = await getProfile(user.user!.username.toString());
  Navigator.of(context, rootNavigator: true).pop();
  Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => ProfilePage(userbio: result)),
  );
} catch (e) {
  Navigator.of(context, rootNavigator: true).pop();
  // 这里可以添加错误提示
  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(content: Text("请求失败:${e.toString()}")),
  );
}

内容的提问来源于stack exchange,提问作者Ali K

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 04:45:30