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

Flutter pop操作前如何显示全局CircularProgressIndicator加载提示

实现方案

要在异步操作全程显示顶层加载指示器,直接用模态弹窗做全局遮罩即可,实现时注意几个关键点:

  • 弹窗设置为不可通过点击遮罩/返回键关闭,避免加载过程中用户误触打断流程
  • 所有异步逻辑(上传、数据写入)要放在弹窗显示之后执行
  • 无论逻辑执行成功还是抛出异常,都要先关闭加载弹窗,避免弹窗永久卡在页面上
  • 关闭加载弹窗时使用根导航栈操作,避免路由嵌套导致的pop错位问题

不要在异步逻辑执行完成前提前关闭弹窗,否则会出现用户提前操作引发的时序异常。

修正后的完整代码如下:

onTap: () async {
  // 弹出顶层加载遮罩
  showDialog(
    context: context,
    barrierDismissible: false,
    builder: (dialogContext) {
      return WillPopScope(
        onWillPop: () async => false, // 禁止返回键关闭弹窗
        child: Center(
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 28, vertical: 24),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12)
            ),
            child: const Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                CircularProgressIndicator(),
                SizedBox(height: 16),
                Text(
                  "正在提交内容,请稍候...",
                  style: TextStyle(fontSize: 15),
                )
              ],
            ),
          ),
        ),
      );
    }
  );

  try {
    // 原有业务逻辑
    if (image11 != null) {
      await uploadImage1(image11);
    }
    await firestor.add({
      "Doc": docs.text,
      "gear": gear.text,
      "price": price.text,
      "1stpic": imageUrl1,
    });
  } catch (e) {
    // 异常场景先关闭加载弹窗,再做错误提示
    Navigator.of(context, rootNavigator: true).pop();
    // 可自行添加错误提示逻辑,比如SnackBar弹出报错信息
    return;
  }

  // 所有逻辑执行完成,先关闭加载遮罩
  Navigator.of(context, rootNavigator: true).pop();
  // 最后退出当前页面
  await Navigator.pop(context);
},

如果需要调整遮罩样式,直接修改showDialog的barrierColor参数、弹窗内部的布局即可,比如要全透明遮罩就设置barrierColor: Colors.transparent。

内容的提问来源于stack exchange,提问作者Mt Khalifa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 17:45:38