如何使用go_router导航至无路径的ShellRoute?
解决GoRouter中ShellRoute导航缺失Scaffold的问题
问题核心:直接跳转ShellRoute下的子路由路径时,GoRouter只会加载子页面,不会触发ShellRoute的pageBuilder(也就是你的BasePage不会被渲染),所以底部导航栏和Scaffold没显示。
正确做法:给ShellRoute设置父路径,导航到该父路径
修改ShellRoute,添加根路径
给你的ShellRoute加上path属性,让它成为一个可导航的入口:ShellRoute( navigatorKey: _shellNavigatorKey, path: '/app', // 新增ShellRoute的根路径 pageBuilder: (_, __, child) => NoTransitionPage(child: BasePage(child: child)), routes: [ GoRoute( path: Paths.home, // 最终拼接路径为 /app/${Paths.home} pageBuilder: (context, state) => const NoTransitionPage( child: HomePage(), ), ), // ...其他子路由 ], ),调整路由初始化配置
确保你的GoRouter初始路由指向FirstPage:final GoRouter router = GoRouter( initialLocation: '/first', routes: [ GoRoute( path: '/first', pageBuilder: (context, state) => NoTransitionPage(child: FirstPage()), ), // 上面修改后的ShellRoute ], );在FirstPage中导航到ShellRoute
使用context.go或context.push导航到ShellRoute的根路径,GoRouter会自动加载BasePage并嵌套显示默认的子路由(这里是HomePage):// 替换当前页面(退出FirstPage,进入BasePage+HomePage) context.go('/app'); // 或者入栈(保留FirstPage在栈中) // context.push('/app');如果需要直接跳转到ShellRoute下的指定子路由,也可以导航到完整拼接路径:
context.go('/app/${Paths.home}');
为什么之前的方法不行?
当你直接context.push(Paths.home)时,GoRouter会直接匹配对应的GoRoute,完全绕过了ShellRoute的pageBuilder逻辑,因此承载Scaffold和底部导航的BasePage不会被渲染,自然看不到这些UI元素。
内容的提问来源于stack exchange,提问作者Miro
相关产品推荐
相关产品推荐

