Sub topic 11
Setting up go_router
This chapter covers how to add go_router to a Flutter app and configure it. It assumes you know Dart syntax including async and await, basic widgets such as Scaffold and AppBar, and what BuildContext is. You should also have seen Navigator.push and Navigator.pop in earlier chapters, along with the idea of declarative navigation and the Router API.
Why go_router
go_router is a package published by the Flutter team. It sits on top of the Router API and gives you a simpler way to describe navigation. You declare a list of URL-like paths and the screen each path shows. The package turns that list into the pages the Navigator displays.
Compared with raw Navigator and onGenerateRoute, you gain:
- One place that lists every screen in the app.
- Paths such as
/products/42that work the same on mobile, web, and desktop. - Built-in support for redirects, nested navigation, and deep links, which later chapters use.
Adding the package
Add the dependency from your project folder:
flutter pub add go_routerThis adds a line like go_router: ^14.0.0 to pubspec.yaml. The version number will differ. Then import it where you build the router:
import 'package:go_router/go_router.dart';The three pieces of a basic setup
A working setup has three parts.
- A
GoRouterobject that holds the configuration. - A tree of
GoRouteobjects inside it. Each one has apathand abuilder. MaterialApp.router, which replaces the plainMaterialAppand receives the router throughrouterConfig.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GoRouter _router = GoRouter(
initialLocation: '/',
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
routes: [
GoRoute(
path: 'products/:id',
builder: (context, state) {
final id = state.pathParameters['id']!;
return ProductScreen(id: id);
},
),
],
),
],
);
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(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('/products/42'),
child: const Text('Open product 42'),
),
),
);
}
}
class ProductScreen extends StatelessWidget {
const ProductScreen({super.key, required this.id});
final String id;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Product $id')),
body: Center(child: Text('Details for product $id')),
);
}
}
void main() => runApp(const MyApp());The HomeScreen and ProductScreen classes are included so the example runs as shown.
Reading the configuration
Declare the router once
Declare the GoRouter as a top-level or long-lived field, not inside build. If you create it inside build, every rebuild makes a new router and the app can lose its current location. In the example, _router is a top-level final.
Paths and nesting
A top-level route needs a path that starts with /. A child route listed in routes uses a path without the leading slash. In the example, the child path products/:id combines with its parent / to give the full path /products/42.
The :id segment is a path parameter. Its value for the current URL is available in state.pathParameters, which is a Map<String, String>. Values are always strings, so convert them yourself when you need an int. Path parameters get their own chapter later.
The builder
builder receives a BuildContext and a GoRouterState. It returns the widget for that route. The state object also holds matchedLocation, uri, and extra. Treat the builder like any build method. It can run more than once, so keep it free of side effects.
go versus push
go_router adds two main navigation methods to BuildContext. They behave differently, and mixing them up is a common source of confusion.
| Method | What it does | Back button result |
|---|---|---|
| `context.go('/products/42')` | Replaces the current location with the full stack that the path describes | Goes to the parent route if one exists, otherwise leaves the app |
| `context.push('/products/42')` | Adds a new screen on top of the current stack | Returns to the screen that called `push` |
With go, the stack is rebuilt from the path. Because products/:id is a child of /, going to /products/42 produces a stack of Home and then Product. The back button therefore shows Home. This matches how a URL on the web works.
With push, the stack is whatever it was, plus one more page. Use push when you want a result back or when the target is a temporary screen. Use go when the destination is a place in the app's structure.
context.pop() removes the top page, as Navigator.pop does. context.pop(value) passes a result, and await context.push<T>(...) receives it. The same null-and-mounted care applies as with Navigator.push: the result is null if the user leaves with the back button, and you should check context.mounted after the await.
Named routes in go_router
You can give a route a name and navigate by name. This avoids typing path strings in many places.
GoRoute(
name: 'product',
path: 'products/:id',
builder: (context, state) =>
ProductScreen(id: state.pathParameters['id']!),
),
// Later, inside a widget:
// context.goNamed('product', pathParameters: {'id': '42'});Names must be unique across the whole router. If you give two routes the same name, go_router throws an assertion error in debug mode. Paths and names are both valid. Pick one style for the project and keep to it.
Handling unknown paths
When no route matches, go_router shows a default error page. You can replace it with errorBuilder:
final GoRouter router = GoRouter(
routes: [
GoRoute(path: '/', builder: (context, state) => const HomeScreen()),
],
errorBuilder: (context, state) => Scaffold(
appBar: AppBar(title: const Text('Not found')),
body: Center(child: Text('No page for ${state.uri}')),
),
);This runs for typos in context.go calls and for links from outside the app that point at paths you never defined.
Common errors
- Using
MaterialAppinstead ofMaterialApp.router. The router is ignored, or you see an error thatrouterConfigis not a parameter. Switch to the.routerconstructor. - A leading slash on a child path. Writing
/products/:idunder a parent route throws an assertion error, because child paths must be relative. Useproducts/:id. - Calling
context.gowith a path that has no route. You land on the error page. Check the spelling and the nesting. - Expecting
goto keep the previous screen. It rebuilds the stack from the path. If you need the previous screen to stay, usepush. - Creating the router inside
build. The router is rebuilt and state is lost. Hold it in a top-level or long-lived field. - Parsing path parameters as the wrong type.
state.pathParameters['id']is aString. Callingint.parseon a bad value throws aFormatException, so useint.tryParsewhen the value comes from a URL a user can edit.
Checking your setup
After you run the example, check these points:
- The app opens on Home because
initialLocationis/. - Tapping the button shows Product 42, and the AppBar shows an automatic back arrow.
- Pressing the back arrow returns to Home.
- If you change the button to
context.go('/missing'), you see the error page.
If the back arrow does not appear, confirm that the product route is a child of / and not a sibling at the top level. A sibling route has no parent in the stack, so go shows it alone.
Exercise
In a router, / has a child route with path products/:id. You call context.go('/products/7') from Home, and then press the system back button. Which screen do you see, and why? What would you call instead if you wanted Home to stay underneath no matter how the routes are nested?
Show answer
You see Home. go rebuilds the stack from the path, and because products/:id is a child of /, the stack is Home then Product. Back removes Product. To keep the current screen underneath regardless of nesting, call context.push('/products/7'), which adds a page on top of the existing stack.
Exercise
A teammate writes GoRoute(path: '/products/:id', ...) inside the routes list of the / route and the app fails an assertion at startup. What is wrong, and how do you fix it? Then explain how to read id as an integer safely.
Show answer
Child routes must use relative paths, so the leading slash is not allowed. Change the path to products/:id. To read the id safely, use final id = int.tryParse(state.pathParameters['id'] ?? ''); and show an error or not-found screen when the result is null.