Flutter如何用PopScope实现双击返回关闭应用(替代已弃用的WillPopScope)
用PopScope替代弃用的WillPopScope实现双击返回关闭功能
Dart 3.2.3对应Flutter版本中,WillPopScope已被PopScope替代,以下是用PopScope实现双击返回按钮关闭窗口的完整代码:
return PopScope( canPop: false, // 禁用默认返回行为,交由自定义逻辑控制 onPopInvoked: (bool didPop) async { // didPop为true时表示系统已处理弹出动作,直接返回 if (didPop) return; final now = DateTime.now(); // 在GetX Logic中维护上次点击返回的时间变量 if (logic._lastPressedAt == null || now.difference(logic._lastPressedAt!) > const Duration(seconds: 1)) { logic._lastPressedAt = now; // 提示用户再按一次返回退出,这里用GetX Snackbar示例 Get.snackbar('提示', '再按一次返回退出'); } else { // 执行窗口关闭操作 Navigator.of(context).pop(); } }, child: Scaffold( body: SafeArea( child: Obx( () => IndexedStack( index: logic.currentIndex.value, children: logic.pages, ), ), ), ), );
关键逻辑说明:
canPop: false:关闭系统默认的返回触发逻辑,让自定义回调完全接管返回行为onPopInvoked回调:用户触发返回操作时自动调用,didPop参数用于判断系统是否已完成弹出动作- 双击判断:通过记录上次点击的时间戳,对比两次点击间隔是否小于设定阈值(示例为1秒),满足条件则执行关闭,否则给出提示
需要在你的GetX Logic类中添加变量维护上次点击时间:
// 在Logic类内部声明 DateTime? _lastPressedAt;
内容的提问来源于stack exchange,提问作者Rahul C
相关产品推荐
相关产品推荐

