如何在StatefulShellRoute之上推送GoRoute路由?
解决方案:让Orders页面叠加在MainPage之上
修改路由配置
将/orders路由从根/路由的子路由中移出,作为GoRouter的直接子路由,并确保它使用rootNavigatorKey作为父导航器键:
final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root'); final GlobalKey<NavigatorState> bottomHomeNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'bottomHomeNavigatorKey'); final GlobalKey<NavigatorState> bottomSecondNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'bottomSecondNavigatorKey'); final GoRouter router = GoRouter( initialLocation: '/home', navigatorKey: rootNavigatorKey, routes: [ GoRoute( path: '/', redirect: (context, state) { if (state.fullPath == null || state.fullPath == '/') { return '/home'; } return state.fullPath; }, parentNavigatorKey: rootNavigatorKey, routes: [ StatefulShellRoute.indexedStack( builder: (context, state, child) => MainPage(child: child), parentNavigatorKey: rootNavigatorKey, branches: [ StatefulShellBranch( navigatorKey: bottomHomeNavigatorKey, routes: [ GoRoute( path: 'home', parentNavigatorKey: bottomHomeNavigatorKey, builder: (context, state) => const HomePage(), ), ], ), StatefulShellBranch( navigatorKey: bottomSecondNavigatorKey, routes: [ GoRoute( path: 'second', parentNavigatorKey: bottomSecondNavigatorKey, builder: (context, state) => const SecondPage(), ), ], ), ], ), ], ), // 将orders路由移到根层级,使用根导航器 GoRoute( path: '/orders', parentNavigatorKey: rootNavigatorKey, builder: (context, state) => const OrdersPage(), routes: [ GoRoute( path: ':orderId', parentNavigatorKey: rootNavigatorKey, builder: (context, state) => SingleOrderPage( orderId: state.pathParameters['orderId'], ), ), ], ), GoRoute( path: '/splash', parentNavigatorKey: rootNavigatorKey, builder: (context, state) => const SplashPage(), ), ], );
为什么这样修改有效
- 原配置中,
/orders是根/路由的子路由,与StatefulShellRoute同级,跳转时会替换掉StatefulShellRoute渲染的MainPage内容,因为它们共享同一个父路由的导航栈。 - 修改后,
/orders成为根导航器的直接子路由,使用rootNavigatorKey作为父导航器。此时跳转/orders时,根导航器会将页面push到栈顶,而MainPage所在的StatefulShellRoute页面依然保留在根导航栈中,从而实现叠加效果。
跳转方式
在页面中直接使用标准的GoRouter跳转方法即可:
// 从HomePage或SecondPage跳转OrdersPage context.push('/orders');
如果需要跳转到单个订单页面:
context.push('/orders/123');
内容的提问来源于stack exchange,提问作者Дмитрий Шелыгин
相关产品推荐
相关产品推荐

