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

使用go_router时点击设备返回键应用直接退出的问题排查

问题原因与解决方案

问题根源

你使用context.go(RouteNames.dashboard)跳转时,go()方法的作用是替换当前路由栈中的页面。从SplashScreen跳转后,路由栈里只剩下DashBoard页面,此时按设备返回键,因为栈中没有上一页,所以直接退出应用。而Flutter默认的Navigator.push()是往路由栈中添加新页面,栈内同时保留SplashScreen和DashBoard,因此返回键可以回到上一页。

解决办法

办法1:改用context.push()跳转

如果希望按返回键能回到SplashScreen,将跳转代码修改为:

context.push(RouteNames.dashboard);

push()会将DashBoard添加到现有路由栈顶部,保留SplashScreen在栈中,返回时即可回到原页面。

办法2:保持context.go()但调整路由逻辑(适合闪屏页仅启动一次的场景)

如果你的需求是闪屏页仅在应用启动时显示,后续无需返回,那当前返回退出的行为是符合预期的。若想让DashBoard成为根页面,同时保留闪屏页的启动逻辑,可以通过redirect配置路由:

修改Routes类中的goRoute配置:

static GoRouter goRoute = GoRouter(
  initialLocation: '/',
  routes: [
    GoRoute(
      path: splash,
      name: splashName,
      builder: (context, state) => const SplashScreen(),
    ),
    GoRoute(
      path: dashboard,
      name: dashboardName,
      builder: (context, state) => const DashBoard(),
    ),
  ],
  // 添加redirect逻辑,根据初始化状态自动跳转
  redirect: (context, state) {
    // 替换为你的初始化完成判断逻辑,比如是否加载完配置、用户信息等
    bool isAppInitialized = false; 

    if (isAppInitialized && state.location == splash) {
      return dashboard;
    }
    return null; // 返回null表示不跳转,保持当前页面
  },
);

在SplashScreen中完成初始化后,更新isAppInitialized状态,路由会自动跳转到DashBoard,此时DashBoard作为栈底页面,返回键直接退出应用,符合闪屏页的设计逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 21:12:37