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

Flutter升级后WillPopScope已废弃,求替换为PopScope的代码帮助

将WillPopScope替换为PopScope的返回提示逻辑实现

替换后的完整代码

// 在当前页面的State类中定义时间变量
DateTime timeBackPressed = DateTime.now();

// 页面中的PopScope组件
PopScope(
  canPop: false, // 禁用默认返回行为,交由自定义逻辑处理
  onPopInvoked: (bool didPop) async {
    if (didPop) return;

    final difference = DateTime.now().difference(timeBackPressed);
    final isExitWarning = difference >= const Duration(seconds: 2);
    timeBackPressed = DateTime.now();

    if (isExitWarning) {
      Fluttertoast.showToast(msg: "再按一次退出", fontSize: 15);
    } else {
      Fluttertoast.cancel();
      // 手动触发页面退出
      if (context.mounted) {
        Navigator.of(context).pop();
      }
    }
  },
  child: // 此处放置原WillPopScope包裹的页面内容
)

关键改动说明

  • 用PopScope替代已废弃的WillPopScope,通过canPop: false接管返回事件的控制权
  • 核心回调onPopInvoked的参数didPop用于判断是否已完成弹出操作,我们只处理未弹出的场景
  • 原逻辑中通过返回值控制是否退出的方式,改为手动调用Navigator.of(context).pop()实现退出,同时增加context.mounted检查避免上下文失效
  • 保留了原有的时间差判断、Toast提示与取消逻辑,确保功能和旧代码完全一致

内容的提问来源于stack exchange,提问作者Othman Sami Dheyab

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 03:14:52