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
相关产品推荐
相关产品推荐

