Sub topic 2
Setting up GoRouter with MaterialApp.router
This chapter assumes you know Dart and Flutter widgets, and that you have used Navigator.push and Navigator.pop. After it, you can add go_router to a project, build a GoRouter, and attach it to the app. You can also diagnose the setup errors that come up most often.
Installing the package
go_router is published on pub.dev and maintained by the Flutter team. Add it from the project root:
flutter pub add go_routerThis adds a go_router line under dependencies in pubspec.yaml. Import it with package:go_router/go_router.dart.
What MaterialApp.router changes
A plain MaterialApp owns a Navigator and a stack of pages that you change with push and pop. MaterialApp.router hands that job to a router. The router turns a location, such as /books/42, into a list of pages. It also turns changes to that list back into locations.
Flutter's lower-level Router API splits this work across three objects. go_router builds all three for you and exposes them as one RouterConfig.
| Piece | What it does | Who creates it |
|---|---|---|
| `RouteInformationProvider` | Supplies the current location, for example from the browser URL bar or an OS deep link | `GoRouter` |
| `RouteInformationParser` | Matches a location against your route tree | `GoRouter` |
| `RouterDelegate` | Builds the `Navigator` and its pages from the match | `GoRouter` |
Without go_router, you would pass these three objects to MaterialApp.router separately. With it, you pass a single routerConfig.
The redirect step in the diagram is covered in a later chapter. For now, note that every location passes through the router before any page is built.
A complete minimal setup
The program below runs as written once go_router is installed. It has two screens, one route per screen, and a button that moves between them.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GoRouter _router = GoRouter(
initialLocation: '/',
debugLogDiagnostics: true,
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
),
GoRoute(
path: '/about',
builder: (context, state) => const AboutScreen(),
),
],
);
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'Router demo',
theme: ThemeData(useMaterial3: true),
routerConfig: _router,
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(
child: ElevatedButton(
onPressed: () => context.go('/about'),
child: const Text('About'),
),
),
);
}
}
class AboutScreen extends StatelessWidget {
const AboutScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('About')),
body: const Center(child: Text('About this app')),
);
}
}The next sections explain each decision in this file.
The GoRouter constructor
Only routes is required. The parameters you will use most often are these:
routesis the list ofRouteBaseobjects, usuallyGoRoute, that make up the route tree. The next chapter covers paths in detail.initialLocationis the location shown at startup. It defaults to/. On the web, the browser's current URL takes precedence over it.debugLogDiagnosticsprints each navigation event and match result to the console. It is off by default. Turn it on in development, because it shows exactly which route a location matched.redirectandrefreshListenableguard routes. Later chapters cover them.errorBuildershows a screen for locations that match no route.navigatorKeyis aGlobalKey<NavigatorState>for the root navigator. It lets code outside the widget tree show dialogs or open pages.observersis a list ofNavigatorObserverobjects, for example for analytics.redirectLimitcaps how many chained redirects are allowed before the router raises an error. The default is 5.
Each top-level GoRoute path must start with /. A nested route's path must not, because it is resolved against its parent. A top-level path without the slash fails an assertion at startup.
Where to create the router
Create the GoRouter once and keep it for the life of the app. The simplest way is a top-level final, as in the example. A GoRouter holds the current navigation state, so replacing it discards that state.
The common mistake is building it inside build:
class BrokenApp extends StatelessWidget {
const BrokenApp({super.key});
@override
Widget build(BuildContext context) {
// Wrong: a new router is created on every rebuild.
final router = GoRouter(
routes: [
GoRoute(path: '/', builder: (context, state) => const Text('Home')),
],
);
return MaterialApp.router(routerConfig: router);
}
}Whenever BrokenApp rebuilds, for example after a theme change above it, the user is sent back to initialLocation. If the router needs values that exist only at runtime, such as an injected auth object, create it in initState of a StatefulWidget and store it in a field. Do not create it in build.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class AppRoot extends StatefulWidget {
const AppRoot({super.key});
@override
State<AppRoot> createState() => _AppRootState();
}
class _AppRootState extends State<AppRoot> {
late final GoRouter _router;
@override
void initState() {
super.initState();
_router = GoRouter(
routes: [
GoRoute(path: '/', builder: (context, state) => const Text('Home')),
],
);
}
@override
void dispose() {
_router.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp.router(routerConfig: _router);
}
}A router created this way should be disposed in dispose. A top-level router lives as long as the process, so it needs no disposal.
Common setup errors
- "No GoRouter found in context." You called
context.gobelow a plainMaterialApp, or above the app widget. UseMaterialApp.routerand callcontext.gofrom a descendant of it. - Passing both
homeandrouterConfig.MaterialApp.routerhas nohome,routes, oronGenerateRoute. Move every screen into theGoRouter. - Hot reload keeps the old route table. A top-level
finalis not rebuilt on hot reload, so edits to the route list may not appear. Use hot restart after changing routes. - A route that never matches. Turn on
debugLogDiagnosticsand read the log. A missing leading slash on a top-level path and a wrong parent path are the usual causes.
You can read the router from any descendant widget with GoRouter.of(context). The context.go and context.push helpers are shorthand for calling the same methods on that instance.
Exercise
A teammate wraps GoRouter(...) inside the build method of the root widget. Users report that changing the app's theme sends them back to the home screen. Explain why this happens and give two ways to fix it.
Show answer
Each rebuild of the root widget creates a new GoRouter. The new router starts at initialLocation and has none of the previous navigation state, so the user lands on the home screen. Fix it by declaring the router as a top-level final, which is built once. Alternatively, create it in initState of a StatefulWidget, store it in a late final field, and pass that field to MaterialApp.router. In the second case, dispose it in dispose.
Exercise
Which two of these GoRoute paths are valid as top-level routes: 'settings', '/settings', '/profile/:userId', 'profile/:userId'?
Show answer
'/settings' and '/profile/:userId'. A top-level path must start with /. Paths without a leading slash are used only for routes nested under a parent.