Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 73 ยท Navigation

Declarative Routing with go_router

Use go_router in Flutter: a route table, path and query parameters, nested and shell routes, redirects for login guards, deep links and the difference from Navigator.

With plain Navigator.push you describe actions: "put this screen on top". That is fine for a few screens, but it gets awkward when you need web URLs, links that open a specific screen from outside the app, bottom tabs that keep their own history, and login guards. These needs are about where the app is, not about what button was pressed.

Declarative routing flips the approach: you declare a table of locations (like /recipes/42), and the router works out which screens must be on the stack for the current location. The most widely used package for this is go_router, maintained by the Flutter team. It builds on the same Navigator you met in Navigator and routes.

Real vs stand-in. go_router is a package that is not available on this site, so its Dart code is read-only. The version number and some parameter names change between releases, so check the package page for your version. The live example is a JavaScript stand-in that matches paths against a route table, builds the stack and applies a redirect.

Why a router package

Deep links Open /recipes/42 straight from a link.
Web URLs The address bar and back button work.
Guards Redirect logged-out users.
Tabs Each tab keeps its own stack.
1 / 2

Setting up

Add the package with flutter pub add go_router, then replace MaterialApp with MaterialApp.router:

DART
import 'package:go_router/go_router.dart';

final GoRouter router = GoRouter(
  initialLocation: '/',
  routes: [
    GoRoute(
      path: '/',
      builder: (context, state) => const HomePage(),
    ),
    GoRoute(
      path: '/about',
      builder: (context, state) => const AboutPage(),
    ),
  ],
);

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerConfig: router,
      title: 'Recipes',
    );
  }
}

Create the GoRouter once, outside build, so a rebuild does not reset navigation.

DART
context.go('/about');          // go to this location (replaces the stack to match it)
context.push('/about');        // add on top, keep what is below
context.pop();                 // back; context.pop('result') returns a value

The difference is the key idea. go says "the app is now at this location" and the stack is rebuilt to fit. push says "put one more screen on top", like the old Navigator, and await context.push<T>() returns a result the same way. On the web, both change the URL.

Path and query parameters

A :name segment captures a value. Query parameters come after ?.

DART
GoRoute(
  path: '/recipes/:id',
  builder: (context, state) {
    final id = int.parse(state.pathParameters['id']!);
    final tab = state.uri.queryParameters['tab'] ?? 'ingredients';
    return RecipePage(id: id, initialTab: tab);
  },
)

// Using it:
context.go('/recipes/42?tab=steps');

Everything arrives as a string, so parse it, and decide what to do for a bad value (for example, show a "not found" page instead of crashing in int.parse; use int.tryParse). Putting the ID in the URL rather than a whole object is deliberate: the URL must be enough to rebuild the screen after a restart or from a shared link. You then load the data for that ID (see HTTP requests and JSON). For richer objects, extra can carry an in-memory value (context.push('/r', extra: recipe)), but extra is lost on web refresh and deep links, so never rely on it alone.

Nested routes

Child routes are relative and are added on top of their parent, so the stack contains both screens:

DART
GoRoute(
  path: '/recipes',
  builder: (context, state) => const RecipeListPage(),
  routes: [
    GoRoute(
      path: ':id',                               // full path: /recipes/:id
      builder: (context, state) =>
          RecipePage(id: int.parse(state.pathParameters['id']!)),
    ),
  ],
)

context.go('/recipes/42') shows RecipePage with RecipeListPage below it, so the app bar has a back button. If the child were written as a separate top-level route, there would be nothing underneath it.

Named routes and type safety

Give routes a name and avoid repeating path strings:

DART
GoRoute(name: 'recipe', path: '/recipes/:id', builder: ...);

context.goNamed('recipe', pathParameters: {'id': '42'});

The companion package go_router_builder can generate typed route classes from annotations, which removes string mistakes. It is optional.

Shell routes: bottom navigation

Apps with a NavigationBar (Material tour) want the bar to stay while the content changes. StatefulShellRoute.indexedStack gives each tab its own navigation stack and keeps it alive:

DART
StatefulShellRoute.indexedStack(
  builder: (context, state, navigationShell) {
    return Scaffold(
      body: navigationShell,
      bottomNavigationBar: NavigationBar(
        selectedIndex: navigationShell.currentIndex,
        onDestinationSelected: (i) => navigationShell.goBranch(
          i,
          initialLocation: i == navigationShell.currentIndex, // tap again = back to tab root
        ),
        destinations: const [
          NavigationDestination(icon: Icon(Icons.home), label: 'Home'),
          NavigationDestination(icon: Icon(Icons.search), label: 'Search'),
        ],
      ),
    );
  },
  branches: [
    StatefulShellBranch(routes: [
      GoRoute(path: '/', builder: (c, s) => const HomePage()),
    ]),
    StatefulShellBranch(routes: [
      GoRoute(path: '/search', builder: (c, s) => const SearchPage()),
    ]),
  ],
)

A plain ShellRoute also wraps child routes in a shared frame, but without preserving each branch's separate stack.

Redirects and guards

redirect runs before a location is shown. Return a new path to send the user elsewhere, or null to let them through. This is where login guards live:

DART
final GoRouter router = GoRouter(
  refreshListenable: authState,          // re-run redirect when login changes
  redirect: (context, state) {
    final loggedIn = authState.isLoggedIn;
    final goingToLogin = state.matchedLocation == '/login';

    if (!loggedIn && !goingToLogin) {
      return '/login?from=${Uri.encodeComponent(state.uri.toString())}';
    }
    if (loggedIn && goingToLogin) return '/';
    return null;
  },
  routes: [ /* ... */ ],
);

refreshListenable takes a Listenable such as a ChangeNotifier (see Lifting state up and ValueNotifier), so logging in or out re-evaluates the redirect immediately. Keep redirects fast and free of async work, and avoid loops (A redirects to B, B redirects to A). The router stops after a limit and reports an error.

A redirect is UI routing, not security. Real protection happens on your server and in the data you fetch. See Security in Flutter apps.

Because every screen has a path, an incoming link such as https://example.com/recipes/42 can open the right screen. The router side is already done by your route table. The platform side needs setup: Android App Links in AndroidManifest.xml and a assetlinks.json file on your domain, iOS Universal Links with an associated-domains entitlement and an apple-app-site-association file. On the web it works by default. Two practical details: handle unknown paths with errorBuilder (a friendly "page not found"), and remember that a deep link may arrive while no user is logged in, which is why the from parameter above exists.

Stand-in: matching, the stack and a redirect

The simulator turns a location into a stack of screens by matching nested routes and applies a login redirect. The real package does far more (encoding, pop handling, transitions), but the core idea is the same.

JS A mini route table with params and a guard

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at the second line of each group: /recipes/42 produces a two-screen stack, RecipeList > RecipeDetail, which is what makes a back button appear. The logged-out case shows the guard: the deep link is saved in from so you can return to it after login.

Common mistakes

  • Creating GoRouter inside build, which resets navigation on every rebuild.
  • Using go when you meant push (and losing the screen below), or the reverse.
  • Relying on extra for data that must survive a refresh or deep link.
  • Parsing parameters without handling bad values.
  • Absolute child paths (starting with /) inside a parent's routes, which Flutter rejects.
  • Treating redirects as security.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main difference between context.go('/a') and context.push('/a') in go_router?

    go is declarative: the stack follows the location. push is imperative and keeps what is below.
  2. 2. Which line reads the :id from the route /recipes/:id?

    Path parameters are in state.pathParameters as strings. Query values are in state.uri.queryParameters.
  3. 3. What should a redirect callback return to let navigation continue unchanged?

    Returning null means no redirect. Returning a path sends the user there.
  4. 4. Why is putting a whole Recipe object in extra risky for a screen that should support deep links?

    A deep link or refresh only has the URL, so the screen must be able to rebuild from path and query parameters.
  5. 5. What does StatefulShellRoute.indexedStack give you?

    Each branch keeps its own navigation history while the shell (like the bottom bar) stays visible.

Summary

  • go_router maps locations (paths) to screens in a route table used with MaterialApp.router.
  • go replaces the stack to match a location; push adds on top and can return a result.
  • Path parameters (:id) and query parameters arrive as strings; parse and validate them.
  • Nested routes are relative and put the parent screen under the child; shell routes keep tabs and a shared frame.
  • redirect plus refreshListenable implements login guards, but it is routing, not security.
  • Deep links need platform setup, and screens must be rebuildable from the URL alone.

Next: Gestures and Input Handling