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

Flutter项目实现双击返回键退出App的功能咨询

实现双击返回键退出App的方案

针对你的Flutter项目(使用GoRouter路由),可以通过以下步骤添加双击返回键退出功能:

步骤1:添加状态变量

在_MyAppState类中新增变量,用于记录上次点击返回键的时间:

class _MyAppState extends State<MyApp> {
  Locale? _locale;
  ThemeMode _themeMode = FlutterFlowTheme.themeMode;

  late AppStateNotifier _appStateNotifier;
  late GoRouter _router;

  bool displaySplashImage = true;
  // 新增:记录上次返回键点击时间
  DateTime? _lastBackPressTime;

  // ... 保留原有其他代码
}

步骤2:包裹路由组件并处理返回事件

修改build方法,用WillPopScope包裹MaterialApp.router,实现返回键监听逻辑:

@override
Widget build(BuildContext context) {
  return WillPopScope(
    onWillPop: () async {
      // 判断当前是否处于根路由
      if (_router.location == '/') {
        final now = DateTime.now();
        // 两次点击间隔小于2秒则退出应用
        if (_lastBackPressTime == null || now.difference(_lastBackPressTime!) > const Duration(seconds: 2)) {
          _lastBackPressTime = now;
          // 弹出提示
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('再按一次退出应用'),
              duration: Duration(seconds: 2),
            ),
          );
          return false; // 阻止默认返回行为
        } else {
          return true; // 允许退出应用
        }
      } else {
        // 非根路由时,正常返回上一页
        return true;
      }
    },
    child: MaterialApp.router(
      // ... 保留原有MaterialApp.router的所有配置代码
    ),
  );
}

关键逻辑说明

  • 根路由判断:通过_router.location == '/'确认当前是否在应用首页,仅在根路由时触发双击退出逻辑;非根路由时交给GoRouter正常处理页面返回。
  • 双击间隔控制:两次点击返回键的时间差小于2秒时执行退出,否则显示提示并重置点击时间。
  • 提示反馈:第一次点击返回键时,底部弹出SnackBar告知用户操作要求。

注意事项

如果你的根路由路径不是'/',请将判断条件中的'/'替换为实际的根路由路径(比如'/home')。该逻辑仅对Android设备生效,符合你的Android 14设备需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 16:23:10