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

如何解决Flutter中go_router路由重复加载的问题?

解决go_router嵌套导航路由重复加载的问题

针对你用go_router 14.6.0实现嵌套导航时遇到的路由加载两次的问题,核心原因及解决方案如下:

1. 避免重复创建GoRouter实例

你的App组件每次build时,都会调用RouteConfig.returnRouter()生成全新的GoRouter实例,这会导致路由系统重复初始化,进而触发页面两次加载。

修改route_config.dart,把GoRouter实例缓存为全局静态变量,确保整个应用生命周期内只创建一次:

final _rootNavigationKey = GlobalKey<NavigatorState>();

class RouteConfig {
  // 缓存GoRouter实例,仅初始化一次
  static final GoRouter _router = GoRouter(
    navigatorKey: _rootNavigationKey,
    debugLogDiagnostics: true,
    routes: [
      GoRoute(
        path: '/login',
        name: RouteNames.login,
        builder: (context, state) => const LoginPage(),
      ),
      StatefulShellRoute.indexedStack(
        // 指定默认激活第一个分支(对应/projects页面)
        initialIndex: 0,
        builder: (context, state, navigationShell) => LayoutScaffold(
          navigationShell: navigationShell,
        ),
        branches: [
          StatefulShellBranch(
            routes: [
              GoRoute(
                name: RouteNames.projects,
                path: '/projects',
                builder: (context, state) => const ProjectOverview(),
              ),
            ],
          ),
          StatefulShellBranch(
            routes: [
              GoRoute(
                name: RouteNames.settings,
                path: '/settings',
                builder: (context, state) => const SettingsOverview(),
              ),
              GoRoute(
                name: RouteNames.profile,
                path: '/profile',
                builder: (context, state) => const ProfileOverview(),
              ),
            ],
          ),
        ],
      ),
    ],
  );

  static GoRouter returnRouter() {
    return _router;
  }
}

2. 用StatefulShellRoute的initialIndex替代全局initialLocation

之前设置的全局initialLocation: "/projects"会触发一次独立导航,而StatefulShellRoute.indexedStack本身会根据initialIndex加载对应分支页面,两者叠加导致页面被build两次。

改用StatefulShellRoute的initialIndex参数指定默认激活分支(比如initialIndex:0对应第一个分支的/projects页面),同时移除全局initialLocation配置,就能避免重复导航。

额外检查

确保App组件不会因其他原因频繁build(比如父组件状态变化),如果后续重新启用ThemeProvider,建议用Consumer或select来减少不必要的build触发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 03:12:07