Flutter中go_router的statefulShellRoute如何导航到壳外路由并支持返回
解决GoRouter StatefulShellRoute导航到壳外路由并保留返回功能的问题
问题根源在于StatefulShellRoute的每个Tab对应独立的嵌套导航器,默认的context.push()会将页面推入当前Tab的嵌套导航栈,因此底部导航栏依然可见;而context.go()会替换整个导航栈,导致无法返回。以下是两种可行解决方案:
方案一:push时指定使用根导航器
在调用push方法时,添加rootNavigator: true参数,强制将页面推入根导航栈而非当前Tab的嵌套栈:
// 导航到壳外路由 context.push('/outside-page', rootNavigator: true);
这样页面会覆盖整个屏幕(底部导航栏隐藏),且返回时只需调用context.pop()即可回到之前的Tab页面,保留了路由栈的返回逻辑。
方案二:在路由定义中绑定根导航器
- 先定义根导航器的全局Key:
final rootNavigatorKey = GlobalKey<NavigatorState>();
- 初始化GoRouter时传入该Key,并给壳外路由指定
parentNavigatorKey:
final router = GoRouter( navigatorKey: rootNavigatorKey, // 根导航器Key routes: [ // StatefulShellRoute的壳路由定义 StatefulShellRoute.indexedStack( builder: (context, state, navigationShell) { return Scaffold( bottomNavigationBar: BottomNavigationBar( // 底部导航栏配置 items: const [ BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Tab1'), BottomNavigationBarItem(icon: Icon(Icons.settings), label: 'Tab2'), ], currentIndex: navigationShell.currentIndex, onTap: (index) => navigationShell.goBranch(index), ), body: navigationShell, ); }, branches: [ // Tab1的嵌套路由分支 StatefulShellBranch( routes: [ GoRoute( path: '/tab1', builder: (context, state) => const Tab1Page(), ), ], ), // Tab2的嵌套路由分支 StatefulShellBranch( routes: [ GoRoute( path: '/tab2', builder: (context, state) => const Tab2Page(), ), ], ), ], ), // 壳外路由,指定使用根导航器 GoRoute( path: '/outside-page', parentNavigatorKey: rootNavigatorKey, builder: (context, state) => const OutsidePage(), ), ], );
完成配置后,直接调用context.push('/outside-page')即可将页面推入根导航栈,底部导航栏自动隐藏,返回功能正常保留。
内容的提问来源于stack exchange,提问作者Jabi
相关产品推荐
相关产品推荐

