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

Flutter中如何阻止Android设备返回键跳转至启动页?

问题原因分析

你的路由栈中保留了启动页(SplashView)的记录,当在首页按下返回键时,会弹出栈顶的首页路由,回到栈内的启动页。以下是两种直接有效的解决方法:


方案一:跳转首页时清除启动页路由记录

从启动页跳转到首页时,使用Get.offNamed或Get.offAllNamed替代常规的Get.toNamed,这样会将路由栈中的启动页替换为首页,后续按下返回键会直接退出应用,而非回到启动页。

示例代码(SplashView内的跳转逻辑):

// 跳转到首页时替换路由栈
Get.offNamed(Routes.HOME);
// 若需确保栈中仅保留首页,可使用offAllNamed
Get.offAllNamed(Routes.HOME);

同时建议修正路由配置(将启动页与首页的路由分离,避免映射冲突):

abstract class Routes {
  Routes._();
  static const SPLASH = _Paths.SPLASH;
  static const HOME = _Paths.HOME;
}

abstract class _Paths {
  _Paths._();
  static const SPLASH = '/splash';
  static const HOME = '/home';
}

class AppPages {
  AppPages._();

  // 初始页设置为启动页
  static const INITIAL = Routes.SPLASH;

  static final routes = [
    GetPage(
      name: _Paths.SPLASH,
      page: () => const SplashView(),
      binding: SplashBinding(),
    ),
    GetPage(
      name: _Paths.HOME,
      page: () => const HomeView(), // 你的实际首页组件
      binding: HomeBinding(),
    ),
  ];
}

方案二:在首页直接拦截返回键

无需修改跳转逻辑,在首页通过WillPopScope组件拦截返回事件,直接退出应用。

示例代码(首页的build方法):

import 'package:flutter/services.dart';

@override
Widget build(BuildContext context) {
  return WillPopScope(
    onWillPop: () async {
      // 直接退出应用
      SystemNavigator.pop();
      // 返回false阻止默认的返回路由行为
      return false;
    },
    child: Scaffold(
      // 首页内容布局
    ),
  );
}

也可使用GetX自带的返回键监听:

import 'package:flutter/services.dart';

@override
void initState() {
  super.initState();
  Get.backCallback = () {
    SystemNavigator.pop();
    return false;
  };
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 16:35:08