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

使用WillPopScope返回上一页时出现错误

问题解决:WillPopScope配合showDialog返回报错

问题场景

添加WillPopScope组件后,触发返回操作时页面仅显示约半秒就报错,代码中实现了弹窗确认是否返回,但执行后出现异常。

核心原因

Dialog的导航上下文与当前页面上下文冲突:使用当前页面的context弹出Dialog时,Dialog会挂载在当前页面的导航栈下。当用户确认返回后,页面被弹出,此时Dialog的上下文已失效,导致后续导航操作触发错误。

修复方案

1. 给showDialog添加根导航器参数

让Dialog挂载到根导航器上,避免与当前页面导航栈绑定,确保上下文独立。

2. 补全WillPopScope的child属性

必须指定页面主体内容,否则组件无法正常渲染。

修改后完整代码

class _UserCommunicationState extends State<UserCommunication> {
  Future<bool?> showWarning(BuildContext context) async => showDialog<bool>(
        context: context,
        useRootNavigator: true, // 关键修复:使用根导航器
        builder: (context) => BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
          child: AlertDialog(
            title: const Text('确定要取消吗?'),
            actions: [
              ElevatedButton(
                onPressed: () => Navigator.pop(context, false),
                child: const Text('取消'),
              ),
              ElevatedButton(
                onPressed: () => Navigator.pop(context, true),
                child: const Text('确定'),
              ),
            ],
          ),
        ),
      );

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        print('返回按钮被按下!');
        final shouldPop = await showWarning(context);
        return shouldPop ?? false;
      },
      child: Scaffold( // 页面主体内容
        appBar: AppBar(title: const Text('用户沟通页面')),
        body: const Center(
          child: Text('页面内容区域'),
        ),
      ),
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 04:35:19