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

Flutter:Android14+下WillPopScope/PopScope返回逻辑失效求助

问题解决方案

针对Android 14+上PopScope无法正确处理返回逻辑的问题,你需要按照以下方式调整代码,适配新的返回拦截机制:

核心修改点

PopScope的onPopInvoked回调与WillPopScope的onWillPop逻辑差异明显:前者在返回动作触发后执行,canPop参数决定是否允许系统默认返回行为。要实现你的需求,需将canPop设为false拦截默认返回,再在onPopInvoked中自定义逻辑。

完整修改后的代码

class DashBoardView extends GetWidget<DashBoardController> {
  const DashBoardView({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    MySize().init(context);
    getStatusBarColor(color: AppColor.whiteF9F9F9);
    return PopScope(
      // 拦截系统默认返回行为
      canPop: false,
      onPopInvoked: (bool didPop) async {
        if (controller.currentIndex.value == 0) {
          // 首页时弹出退出确认框
          await AppDialog.appAlertDialog(
            context: context,
            description: "确定要退出应用吗?",
            question: '退出应用',
            questionTextStyle: TextStyle(fontSize: 14, color: AppColor.grey, fontWeight: FontWeight.w700),
            onTap: () {
              Get.put(SocketController()).disconnectFromSocket();
              // 用系统推荐方式退出,替代exit(0)
              SystemNavigator.pop();
            },
          );
        } else {
          // 非首页时切换到第一个标签页
          controller.currentIndex.value = 0;
          // Obx会自动响应currentIndex的状态变化,无需手动调用update()
        }
      },
      child: Scaffold(
        body: Obx(() => controller.pages[controller.currentIndex.value]),
        bottomNavigationBar: customBottomNavigation(),
      ),
    );
  }
}

额外注意事项

  • 移除controller.update():Obx监听currentIndex的变化,当currentIndex.value更新时会自动重建UI,无需手动调用。
  • 替换exit(0)为SystemNavigator.pop():exit(0)是强制终止进程,在Android 14+可能触发系统异常检测,SystemNavigator.pop()是Flutter标准退出方式,更符合系统规范。
  • 确保弹窗异步执行:给AppDialog.appAlertDialog加上await,保证弹窗交互完成后再处理后续逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 12:58:13