how to push to root navigator from sub routes when using go_router
Asked Answered
A

1

6

I'm using go_router on flutter, and I have a root routes and a shell route that contains a bottom nav bar on all sub routes. And I want to push a page that is outside of the shell route and I want it to be pushed on the root navigator because it has to be above the bottom nav bar.

I've checked endless documentation of go_router but there is no option to do that.

I have implemented a way to remove all routes and push a page on the root navigator, but when that page is poped it goes to an empty page. but I want it to go to where it was when a page on the shell route.

Armond answered 11/9, 2023 at 18:37 Comment(0)
A
11

I ran into the same problem. Try adding parentNavigatorKeys and navigatorKeys to your GoRouter.

final GlobalKey<NavigatorState> _rootNavigator = GlobalKey(debugLabel: 'root');
final GlobalKey<NavigatorState> _shellNavigator =
    GlobalKey(debugLabel: 'shell');

final GoRouter _router = GoRouter(
  navigatorKey: _rootNavigator,
  routes: <RouteBase>[
    GoRoute(
      parentNavigatorKey: _rootNavigator,
      path: '/login',
      builder: (context, state) => const LoginScreen(),
    ),
    ShellRoute(
      navigatorKey: _shellNavigator,
      builder: (context, state, child) => BottomNav(
        child: child,
      ),
      routes: [
        GoRoute(
          parentNavigatorKey: _shellNavigator,
          path: '/',
          builder: (BuildContext context, GoRouterState state) {
            return const HomeScreen();
          },
          routes: <RouteBase>[
            GoRoute(
              name: 'nested_view',
              path: 'nested-view',
              builder: (BuildContext context, GoRouterState state) {
                return const NestedScreen();
              },
            ),
          ],
        ),
      ],
    )
  ],
);

Then from your code call:

context.push('/login')
Adao answered 14/9, 2023 at 5:25 Comment(2)
Thank you so much! I was stuck on this for way too long and didn't find any solutions or docs on it. This should be the accepted answer.Inexplicit
The lack of official Doc is a big problem for go_router package. Its really a shame since this problem (lack of official doc) has been discussed in their GitHub issue several times before, even back in 2022. But there are still no clear doc like other big package does today, in 2024.Stickpin

© 2022 - 2025 — McMap. All rights reserved.