Learn/Navigation/Modern Navigation with GoRouter

Modern Navigation with GoRouter

Build production-grade declarative routing with GoRouter, path params, auth guards, and ShellRoute

15 min~6 min read+55 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. 1. Setting Up GoRouter
  2. 2. Navigating: `context.go()` vs `context.push()`
  3. 3. 2. Dynamic Path & Query Parameters
  4. 4. 3. Persistent Bottom Navigation with StatefulShellRoute
  5. 5. 4. Auth Guards & Global Redirection
  6. 6. This Lesson In Simple Words
  7. 7. Your level focus
  8. 8. One practical habit
  9. 9. Deep Understanding Guide
  10. 10. Why this lesson matters
  11. 11. Study flow for better retention
  12. 12. Quick Glossary

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

Modern Navigation with GoRouter

Navigation in Flutter has evolved through two distinct eras:

  1. Navigator 1.0 (Imperative): Pushing screens onto a stack manually (Navigator.push(context, MaterialPageRoute(...))). Simple, but struggles with deep links, browser back/forward buttons, and nested bottom navigation.
  2. Navigator 2.0 & GoRouter (Declarative): The UI reflects the current URI path. If the URL changes, Flutter renders the corresponding route hierarchy.

GoRouter is the officially recommended routing package maintained by the Flutter team. In this lesson, we will build a complete production routing system with path parameters, auth guards, and persistent bottom tabs.

1. Setting Up GoRouter

First, ensure go_router is added to your pubspec.yaml. Then, initialize GoRouter as a top-level or singleton instance and wire it into MaterialApp.router.

final appRouter = GoRouter(
  initialLocation: '/',
  routes: [
    GoRoute(
      path: '/',
      builder: (context, state) => const HomeScreen(),
    ),
    GoRoute(
      path: '/details',
      builder: (context, state) => const DetailsScreen(),
    ),
  ],
);

// In main.dart:
class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerConfig: appRouter,
    );
  }
}
  • context.go('/details'): Replaces the navigation hierarchy based on the target URL path. Ideal for deep links and web navigation.
  • context.push('/details'): Pushes a new screen directly on top of the current screen stack, creating a back button regardless of URI hierarchy.

2. Dynamic Path & Query Parameters

Real apps pass dynamic IDs (e.g., /products/42) and filter queries (e.g., /search?query=shoes).

GoRoute(
  path: '/product/:id',
  builder: (context, state) {
    // 1. Extract path parameter (:id)
    final productId = state.pathParameters['id']!;
    
    // 2. Extract query parameter (?ref=promo)
    final referralCode = state.uri.queryParameters['ref'];

    return ProductDetailScreen(
      id: productId,
      referralCode: referralCode,
    );
  },
);

// To navigate:
context.go('/product/101?ref=summer_sale');

Null Safety with Parameters

💡 Null Safety with Parameters

Path parameters defined with :name are guaranteed to match when the route resolves. Query parameters, however, may be omitted by the user, so always handle queryParameters as nullable.

3. Persistent Bottom Navigation with StatefulShellRoute

A classic mobile requirement is a BottomNavigationBar where each tab maintains its own navigation history and scroll position when switching tabs.

GoRouter provides StatefulShellRoute.indexedStack specifically for this pattern:

dart
1final router = GoRouter(
2 initialLocation: '/home',
3 routes: [
4 StatefulShellRoute.indexedStack(
5 builder: (context, state, navigationShell) {
6 // Return your Scaffold holding the BottomNavigationBar
7 return Scaffold(
8 body: navigationShell, // Active branch widget
9 bottomNavigationBar: BottomNavigationBar(
10 currentIndex: navigationShell.currentIndex,
11 onTap: (index) => navigationShell.goBranch(
12 index,
13 initialLocation: index == navigationShell.currentIndex,
14 ),
15 items: const [
16 BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
17 BottomNavigationBarItem(icon: Icon(Icons.person), label: 'Profile'),
18 ],
19 ),
20 );
21 },
22 branches: [
23 // Tab 1 Branch
24 StatefulShellBranch(
25 routes: [
26 GoRoute(path: '/home', builder: (_, __) => const HomeScreen()),
27 ],
28 ),
29 // Tab 2 Branch
30 StatefulShellBranch(
31 routes: [
32 GoRoute(path: '/profile', builder: (_, __) => const ProfileScreen()),
33 ],
34 ),
35 ],
36 ),
37 ],
38);

4. Auth Guards & Global Redirection

Prevent unauthorized users from accessing protected screens using redirect:

final appRouter = GoRouter(
  redirect: (context, state) {
    final bool isLoggedIn = AuthService.instance.isLoggedIn;
    final bool isLoggingIn = state.matchedLocation == '/login';

    // If user is not logged in and not on login screen, redirect to login
    if (!isLoggedIn && !isLoggingIn) return '/login';

    // If user is already logged in and navigates to login, redirect to home
    if (isLoggedIn && isLoggingIn) return '/home';

    // Return null to continue to requested destination
    return null;
  },
  routes: [ /* ... */ ],
);

Avoid Infinite Redirect Loops

⚠️ Avoid Infinite Redirect Loops

Always check if the user is already on the target route (e.g., state.matchedLocation == '/login') before returning a redirect string. Failing to check causes infinite navigation loop exceptions.

Production GoRouter Checklist

  • Use MaterialApp.router with routerConfig instead of legacy routes map.
  • Use pathParameters for mandatory entity IDs and queryParameters for optional filters.
  • Implement StatefulShellRoute.indexedStack for persistent bottom tab states.
  • Guard protected screens using top-level or route-level redirect callbacks.
  • Test deep linking URLs on mobile (Universal Links/App Links) and Web browsers.

This Lesson In Simple Words

Build production grade declarative routing with GoRouter, path params, auth guards, and ShellRoute. Navigation manages how users move between screens and return to previous states.

Your level focus

Connect each concept to real app features you can build.

One practical habit

Design route names and arguments before wiring screen UI.

Deep Understanding Guide

Why this lesson matters

Poor routing decisions create confusing UX and fragile deep-link behavior.

Study flow for better retention

  1. Map the lesson to one screen, one user action, and one expected output.
  2. Think user journey first: open app, enter data, recover state, continue flow.
  3. If you can choose between two approaches and explain why, you are improving.

Common Mistakes To Avoid

  • Passing very large objects through routes instead of IDs or lightweight models.
  • Mixing unrelated navigation methods in the same feature.
  • Losing state on back navigation due to poor route stack handling.
  • Not testing deep links and cold-start navigation paths.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Implement a three-screen flow with named routes and typed arguments.
  • Add one deep-link path and verify expected destination.
  • Write a small route guard for authenticated vs guest users.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "What is the key difference between context.go() and context.push() in GoRouter?".

Quick Glossary

  • state: Data that can change and update what the user sees.
  • build: The method that describes UI for the current state.
  • navigator: A stack manager that controls screen transitions.
  • route: A screen entry managed by the Navigator.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Lesson Completion Checklist

  • I can explain "Modern Navigation with GoRouter" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Passing very large objects through routes instead of IDs or lightweight models.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

What is the key difference between context.go() and context.push() in GoRouter?

context.go() navigates by URI path updating the route tree, while context.push() imperatively pushes a route on top of the current screen.

Which widget should you use in GoRouter to maintain tab state and scroll position across a BottomNavigationBar?

StatefulShellRoute.indexedStack creates independent branch navigators for each tab, preserving state and scroll positions when switching.

How do you extract a path parameter /users/:userId in GoRouter?

GoRouter provides matched path parameters as a map inside state.pathParameters.

What should a GoRouter redirect callback return if no navigation change is needed?

Returning null tells GoRouter to allow the navigation to proceed to the requested target destination without interception.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue