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

Flutter 3.22.0中PopScope的onPopInvoked回调失效问题求助

Flutter 3.22.0 中 PopScope onPopInvoked 不触发的解决方案

不少开发者都碰到过这个问题,Flutter 3.22.0 对 PopScope 的行为做了调整,核心是 onPopInvoked 的触发逻辑变了——现在需要手动控制弹出行为,同时要正确设置 PopScope 的 canPop 属性。

以下是修复后的双击退出示例代码:

bool _isExitPressed = false;

@override
Widget build(BuildContext context) {
  return PopScope(
    // 设置为false,阻止默认弹出行为,交由onPopInvoked处理
    canPop: false,
    onPopInvoked: (bool didPop) async {
      if (didPop) return;

      if (_isExitPressed) {
        // 二次点击,执行退出
        SystemNavigator.pop();
      } else {
        _isExitPressed = true;
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('再按一次退出应用')),
        );
        // 1.5秒后重置标记
        Future.delayed(const Duration(milliseconds: 1500), () {
          _isExitPressed = false;
        });
      }
    },
    child: Scaffold(
      appBar: AppBar(title: const Text('主页')),
      body: const Center(child: Text('双击返回退出')),
    ),
  );
}

关键注意点:

  • 必须把 PopScope 的 canPop 设为 false,否则默认弹出行为会直接执行,不会触发自定义的 onPopInvoked 逻辑
  • 在 onPopInvoked 里先判断 didPop,如果为 true 说明弹出已完成,直接返回即可
  • 退出APP时使用 SystemNavigator.pop(),替代依赖默认的pop行为

如果是嵌套路由场景,还要确保当前页面处于路由栈最顶层,否则可能会触发上层路由的PopScope逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 01:17:01