Navigation and Routing
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
State Management gave Trailhead a place to keep its data; this page
connects the screens that show it. Flutter ships two navigation systems: the imperative Navigator that has existed
since the first release, and the declarative Router introduced with Navigator 2. Most apps do not use Router
directly, because the Flutter team maintains go_router 18.1.4 on top of it, and that is the package used for the
whole running example. Compare this page with the equivalent React Native
navigation story, or with the shared-code approach of Kotlin
Multiplatform. The overview of all approaches lives in Hybrid Apps.
Navigator 1 versus Router
| Aspect | Navigator (imperative) | Router (declarative) |
|---|---|---|
Mental model |
A stack of routes you push and pop with calls such as Navigator.of(context).push(...). |
The whole navigation state is derived from a location (a URL); the page stack follows from it. |
Deep links and web URLs |
Possible with named routes, but limited and awkward for nested paths. |
First-class: every screen has a path, and the operating system or browser can open any of them. |
Back button on the web |
Must be hand-managed. |
The browser history mirrors the location automatically. |
Typical use |
Dialogs, bottom sheets, small apps, and a quick |
Anything with deep links, tabs with their own stacks, redirects, or a web target. |
Both coexist. go_router builds on Router, yet showDialog, showModalBottomSheet and Navigator.pop still work
inside a go_router app, because dialogs are routes on the nearest Navigator.
Adding go_router
flutter pub add go_router
The app switches from MaterialApp to MaterialApp.router and hands it a GoRouter:
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
void main() => runApp(const ProviderScope(child: TrailheadApp()));
class TrailheadApp extends ConsumerWidget {
const TrailheadApp({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final router = ref.watch(routerProvider);
return MaterialApp.router(
title: 'Trailhead',
routerConfig: router,
theme: ThemeData(colorSchemeSeed: Colors.green, useMaterial3: true),
);
}
}
The Trailhead Route Tree
Trailhead has three bottom tabs (Trails, Favourites, Log a hike), a detail screen that lives under the Trails tab, and a sign-in screen outside the tabs.
Configuring GoRouter
The GoRouter is created once and exposed through a Riverpod provider, so the redirect logic can watch the
authentication state:
final routerKey = GlobalKey<NavigatorState>(debugLabel: 'root');
final routerProvider = Provider<GoRouter>((ref) {
final auth = ref.watch(authStateProvider);
return GoRouter(
navigatorKey: routerKey,
initialLocation: '/trails',
debugLogDiagnostics: true,
redirect: (context, state) {
final signedIn = auth.isSignedIn;
final goingToLogin = state.matchedLocation == '/login';
if (!signedIn && !goingToLogin) {
return '/login?from=${Uri.encodeComponent(state.uri.toString())}';
}
if (signedIn && goingToLogin) return '/trails';
return null; // no redirect
},
routes: [
GoRoute(
path: '/login',
builder: (context, state) =>
LoginScreen(from: state.uri.queryParameters['from']),
),
StatefulShellRoute.indexedStack(
builder: (context, state, navigationShell) =>
ScaffoldWithNavBar(navigationShell: navigationShell),
branches: [
StatefulShellBranch(routes: [
GoRoute(
path: '/trails',
builder: (context, state) => TrailListScreen(
query: state.uri.queryParameters['q'] ?? '',
),
routes: [
GoRoute(
path: ':id',
name: 'detail',
builder: (context, state) =>
TrailDetailScreen(id: state.pathParameters['id']!),
),
],
),
]),
StatefulShellBranch(routes: [
GoRoute(
path: '/favourites',
builder: (context, state) => const FavouritesScreen(),
),
]),
StatefulShellBranch(routes: [
GoRoute(
path: '/log',
builder: (context, state) => const LogHikeScreen(),
routes: [
GoRoute(
path: 'camera',
parentNavigatorKey: routerKey,
builder: (context, state) => const CameraScreen(),
),
],
),
]),
],
),
],
);
});
Key points in that configuration:
-
A child route’s
pathis relative (:id), so the full location of the detail screen is/trails/:id; itsname: 'detail'lets callers navigate withgoNamedinstead of building the path. -
parentNavigatorKey: routerKeypushes the camera screen on the root navigator, covering the bottom bar. -
redirectruns before every navigation; returningnullmeans "no redirect", so navigation proceeds to the requested location, and returning a location sends the user there instead. -
state.uriis aUri, so query parameters are available throughstate.uri.queryParameters.
Navigating
| Call | Behaviour |
|---|---|
context.go('/trails/42') |
Replaces the current location, rebuilding the page stack to match the path (declarative). |
context.push('/trails/42') |
Pushes a page on top of the current stack and returns a |
|
Pops the top page, optionally with a result. |
context.pushReplacement('/login') |
Replaces the top page with another. |
context.goNamed('detail', pathParameters: {'id': '42'}) |
Navigates by route name, so renaming a path does not break callers. |
Prefer go for moving between locations and push when the previous screen must stay on the stack and may receive
a result, for example the log-a-hike form returning true after saving.
Bottom Tabs with StatefulShellRoute
ShellRoute wraps child routes in a persistent scaffold, but swapping tabs discards each tab’s own stack.
StatefulShellRoute.indexedStack keeps one navigator per branch inside an IndexedStack, so the trail list
keeps its scroll position and detail screen when the user visits Favourites and returns.
class ScaffoldWithNavBar extends StatelessWidget {
const ScaffoldWithNavBar({super.key, required this.navigationShell});
final StatefulNavigationShell navigationShell;
@override
Widget build(BuildContext context) {
return Scaffold(
body: navigationShell,
bottomNavigationBar: NavigationBar(
selectedIndex: navigationShell.currentIndex,
onDestinationSelected: (index) => navigationShell.goBranch(
index,
// Tapping the active tab pops it back to its first screen.
initialLocation: index == navigationShell.currentIndex,
),
destinations: const [
NavigationDestination(icon: Icon(Icons.terrain), label: 'Trails'),
NavigationDestination(icon: Icon(Icons.favorite), label: 'Favourites'),
NavigationDestination(icon: Icon(Icons.add_a_photo), label: 'Log'),
],
),
);
}
}
Redirect Guards for Authentication
The top-level redirect shown earlier is a guard. Two details matter in practice:
-
The router must be told when the guard’s inputs change. Because the provider above watches
authStateProvider, Riverpod rebuilds the router when the user signs in or out. An alternative is passing aListenabletoGoRouter(refreshListenable: listenable)and keeping a single long-lived router. -
Preserve where the user wanted to go. The sign-in screen reads the
fromquery parameter and callscontext.go(from ?? '/trails')after success.
Route-level redirect callbacks also exist, which suits a guard that only applies to one branch, for example
sending a signed-out user away from /log while leaving the trail list public.
Deep Links
A deep link is a URL that opens the app at a specific screen. With go_router the routing side is already done: every
path in the tree is a deep-link target, so https://trailhead.example.com/trails/42 opens TrailDetailScreen for
trail 42. The operating-system side still needs configuration.
Android App Links
Add an intent filter to the main activity in android/app/src/main/AndroidManifest.xml:
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https" android:host="trailhead.example.com" />
</intent-filter>
Then host https://trailhead.example.com/.well-known/assetlinks.json containing the package name and the SHA-256
fingerprint of the signing certificate. Without the verified file, Android shows a chooser instead of opening the
app directly.
iOS universal links
Enable the Associated Domains capability in Xcode with the entry applinks:trailhead.example.com, and host an
apple-app-site-association file (no extension, served as JSON) at
https://trailhead.example.com/.well-known/apple-app-site-association listing the app identifier and the paths it
handles.
Flutter’s deep-link handling is enabled by default in recent releases; an app that wants to opt out or manage links
itself through a plugin can set the corresponding flag in the Android manifest or Info.plist, as described in the
official deep-linking guide listed under References.
Intercepting the Back Button with PopScope
PopScope replaces the older WillPopScope. It lets a screen veto or react to a pop, for example to protect an
unsaved hike form:
class LogHikeScreen extends StatefulWidget {
const LogHikeScreen({super.key});
@override
State<LogHikeScreen> createState() => _LogHikeScreenState();
}
class _LogHikeScreenState extends State<LogHikeScreen> {
bool dirty = false;
@override
Widget build(BuildContext context) {
return PopScope(
canPop: !dirty,
onPopInvokedWithResult: (didPop, result) async {
if (didPop) return;
final navigator = Navigator.of(context);
final discard = await showDialog<bool>(
context: context,
builder: (_) => AlertDialog(
title: const Text('Discard this hike?'),
actions: [
TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Keep')),
TextButton(onPressed: () => Navigator.pop(context, true), child: const Text('Discard')),
],
),
);
if (discard == true) navigator.pop();
},
child: Scaffold(
appBar: AppBar(title: const Text('Log a hike')),
body: TextField(onChanged: (_) => setState(() => dirty = true)),
),
);
}
}
Typed Routes
Strings such as /trails/42 are easy to mistype. The companion package go_router_builder generates typed route
classes from annotations, so navigation becomes TrailDetailRoute(id: '42').go(context) and the compiler checks
the parameter names and types. It uses code generation (build_runner), the same mechanism as json_serializable
in Data, Storage and Networking. Plain string paths are perfectly
adequate for a small app like Trailhead; typed routes pay off as the tree grows.
Common Pitfalls
-
Calling
context.gofrom a staleBuildContextafter anawait: checkcontext.mountedfirst. -
Forgetting
parentNavigatorKeyand finding a full-screen camera stuck beneath the bottom bar. -
Doing slow work inside
redirect, which runs on every navigation.
Next, see Data, Storage and Networking, and keep the Flutter Cheat Sheet close by. Widgets used in the screens above are explained in Widgets and Layout, and how routes are rendered in Architecture and Rendering.