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

调用context.push('/profile/check')时Go Router的ShellRoute builder函数未触发

问题解决:GoRouter嵌套ShellRoute未触发builder的问题

问题原因

你将ShellRoute直接嵌套在了GoRoute的routes数组中,这不符合GoRouter的路由结构规则——ShellRoute不能作为GoRoute的子路由存在。当调用context.push('/profile/check')时,GoRouter只会匹配到/profile这个GoRoute,然后直接渲染它的子GoRoute(check页面),完全跳过了中间的ShellRoute,导致其builder函数从未被执行。

解决方案

调整路由结构,将/profile对应的路由改为ShellRoute(作为顶级ShellRoute的子路由),在这个新的ShellRoute中定义/profile页面以及它的子页面check和test,这样GoRouter就能正确识别嵌套的导航壳层级,触发对应的builder函数。

修改后的代码示例

late final GoRouter router = GoRouter(
  initialLocation: '/',
  refreshListenable: appService,
  navigatorKey: _rootNavigatorKey,
  routes: <RouteBase>[
    ShellRoute(
      navigatorKey: _rootShellNavigatorKey,
      builder: (BuildContext context, GoRouterState state, child) => AppScaffold(
        child: child,
      ),
      routes: [
        GoRoute(
          parentNavigatorKey: _rootShellNavigatorKey,
          path: '/',
          builder: (BuildContext context, GoRouterState state) {
            return HomeScreen();
          },
        ),
        // 将原/profile的GoRoute替换为ShellRoute,实现嵌套导航壳
        ShellRoute(
          builder: (context, state, child) {
            print('builder function will be called now');
            // 用Column+Expanded避免布局溢出问题,确保子页面正常显示
            return Column(
              children: [
                Text("hello world"),
                Expanded(child: child),
              ],
            );
          },
          routes: [
            // 定义/profile主页面
            GoRoute(
              parentNavigatorKey: _rootShellNavigatorKey,
              path: '/profile',
              builder: (BuildContext context, GoRouterState state) {
                return ProfilePageView();
              },
            ),
            // 定义/profile/check子页面
            GoRoute(
              parentNavigatorKey: _rootShellNavigatorKey,
              path: '/profile/check',
              builder: (BuildContext context, GoRouterState state) {
                return Center(
                  child: Text("Check"),
                );
              },
            ),
            // 定义/profile/test子页面
            GoRoute(
              parentNavigatorKey: _rootShellNavigatorKey,
              path: '/profile/test',
              builder: (BuildContext context, GoRouterState state) {
                return Center(
                  child: Text("Test"),
                );
              },
            ),
          ],
        ),
      ],
    ),
  ],
);

补充说明

修改后,访问/profile时会先渲染子ShellRoute的builder内容(hello world),再嵌套显示ProfilePageView;访问/profile/check或/profile/test时,同样会先渲染子Shell的内容,再嵌套显示对应的子页面,完全符合你想要的嵌套导航壳效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 20:20:26