Sub topic 1
Quick refresher: GoRouter and GoRoute
The rest of this tutorial builds tabbed navigation on top of go_router's core types. Before adding shells and branches, this chapter reviews the pieces they depend on: GoRouter, GoRoute, locations, path and query parameters, and the difference between go and push.
Prerequisites
This chapter assumes you already have the following:
- Dart and Flutter fundamentals:
StatelessWidget,Scaffold, and running an app on an emulator or in the browser. - A basic idea of Flutter's
Navigatorand what a route is. - Familiarity with path-based URLs such as
/books/42?tab=reviews. - A project with the
go_routerpackage added. Runflutter pub add go_routerif it is not there yet.
You do not need any knowledge of ShellRoute or StatefulShellRoute. Later chapters introduce them.
The declarative model
Flutter's classic Navigator API is imperative. You call push and pop and the stack changes step by step. go_router is declarative. You describe a table of locations the app understands, and then you ask to go to one of them. The router works out which pages belong on the stack for that location.
Three terms carry most of the weight:
- A location is a string such as
/books/42?tab=reviews. It is the single source of truth for where the user is. - A route is one entry in the table. A
GoRoutemaps a path pattern to a widget builder. - The router is the
GoRouterobject. It owns the route table, parses locations, and talks to the platform (browser URL bar, deep links, system back button).
A complete minimal app
The following file runs as shown. It defines a home screen and a book details screen nested under it.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
void main() => runApp(const App());
final GoRouter router = GoRouter(
initialLocation: '/',
routes: [
GoRoute(
path: '/',
name: 'home',
builder: (context, state) => const HomeScreen(),
routes: [
GoRoute(
path: 'books/:id',
name: 'book',
builder: (context, state) {
final id = state.pathParameters['id']!;
final tab = state.uri.queryParameters['tab'] ?? 'info';
return BookScreen(id: id, tab: tab);
},
),
],
),
],
);
class App extends StatelessWidget {
const App({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'Router refresher',
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: Column(
mainAxisSize: MainAxisSize.min,
children: [
ElevatedButton(
onPressed: () => context.go('/books/42'),
child: const Text('go to book 42'),
),
ElevatedButton(
onPressed: () => context.push('/books/7?tab=reviews'),
child: const Text('push book 7 (reviews)'),
),
ElevatedButton(
onPressed: () => context.goNamed(
'book',
pathParameters: {'id': '99'},
queryParameters: {'tab': 'reviews'},
),
child: const Text('goNamed book 99'),
),
],
),
),
);
}
}
class BookScreen extends StatelessWidget {
const BookScreen({super.key, required this.id, required this.tab});
final String id;
final String tab;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Book $id')),
body: Center(child: Text('Showing the "$tab" tab of book $id')),
);
}
}Note the entry point. MaterialApp.router takes a routerConfig and replaces the usual home: and routes: arguments of MaterialApp. The GoRouter object is created once, here as a top-level final, and not inside build. Creating it in build would reset navigation on every rebuild.
GoRouter: the configuration object
GoRouter takes more arguments than this chapter uses, but a few come up constantly:
| Argument | Purpose |
|---|---|
| `routes` | The list of top-level `RouteBase` objects (usually `GoRoute`). Required. |
| `initialLocation` | The location shown at startup. Defaults to `/`. |
| `navigatorKey` | A key for the root `Navigator`. A later chapter covers it. |
| `redirect` | A global function that can send the user elsewhere. |
| `errorBuilder` | The widget shown when no route matches a location. |
| `refreshListenable` | A `Listenable` that makes the router re-run redirects when it changes. |
| `debugLogDiagnostics` | Prints matching details to the console. Useful while debugging. |
On the web, the initial location comes from the browser URL and initialLocation is ignored if the URL is already something else. On mobile, a deep link takes precedence in the same way.
GoRoute: path, builder and sub-routes
A GoRoute has three main parts.
pathis a pattern. It can contain literal segments (books) and parameters (:id).builderreceives aBuildContextand aGoRouterState, and returns the screen widget.routesholds optional child routes.
Top-level paths start with /. Child paths do not. In the example, the child is books/:id and its full path is /books/:id. If you write a leading slash on a child, go_router throws an assertion error when the router is created. Remember this rule, because the tabbed apps ahead nest routes several levels deep.
Reading parameters from GoRouterState
GoRouterState describes the match that triggered the builder:
state.pathParametersis aMap<String, String>of values captured by:namesegments.state.uriis aUrifor the whole location, sostate.uri.queryParametersgives the query string.state.extrais an optional object passed withgoorpush. It does not appear in the URL and does not survive a browser refresh, so use it sparingly.state.matchedLocationis the part of the location that matched this route.state.fullPathis the route's full path pattern, with the parameters still in it, such as/books/:id.
All path parameters arrive as strings. Convert them yourself, for example with int.tryParse(id), and handle bad input.
Navigating by location
go_router adds extension methods on BuildContext. Three of them cover most navigation.
context.go(location)replaces the current stack with the stack that matches the location.context.push(location)adds one page on top of the current stack and leaves everything below it alone.context.pop()removes the top page. Usecontext.canPop()to check first.
The difference between go and push matters throughout the tutorial. Suppose the app is at /. After context.go('/books/42'), the stack is two pages: HomeScreen and BookScreen. go_router built the parent page because books/:id is a child of /. Pressing back returns to Home. After context.push('/books/7') from the same place, the new page is added to whatever was already there. Pressing back returns to the previous page, and the stack can hold the same route more than once.
Named routes
Setting name on a route lets you navigate without writing path strings. context.goNamed('book', pathParameters: {'id': '99'}) builds the location /books/99 for you. Names must be unique across the whole router. Two routes with the same name fail an assertion at startup. Named navigation also encodes parameters, so values with spaces or slashes are escaped correctly. With raw strings, you must do that yourself.
When no route matches
If the location matches nothing, go_router shows a built-in error page. Replace it with errorBuilder:
final GoRouter router = GoRouter(
routes: [
GoRoute(path: '/', builder: (context, state) => const HomeScreen()),
],
errorBuilder: (context, state) => Scaffold(
body: Center(child: Text('No route for ${state.uri}')),
),
);Typing a wrong URL in a web build is the easiest way to see this page.
Why this matters for tabs
Everything in a plain GoRouter shares one Navigator, so there is one stack. When the user calls go('/settings') from /home/details/3, the whole stack is replaced. The detail page is gone, and returning to Home later shows a fresh Home. That is correct for simple apps, and it is exactly the behavior a tabbed app does not want. The next chapters show how go_router models a tree of routes and then how StatefulShellRoute gives each tab its own stack.
Quick checklist
Before moving on, check that you can answer these from memory:
- Where do you pass the router to the app? (
MaterialApp.router, viarouterConfig.) - Which child paths start with
/? (None. Only top-level routes do.) - Where do path parameters and query parameters come from? (
state.pathParametersandstate.uri.queryParameters.) - How do
goandpushdiffer in their effect on the stack?
Exercise
An app has this route table: a top-level GoRoute with path '/' and a child GoRoute with path 'books/:id'. The user is on '/' and the code calls context.go('/books/42'), and then context.pop(). Which screen is visible afterwards, and why? What would the stack look like if the code had called context.push('/books/42') instead of go, and then pop?
Show answer
After go('/books/42'), go_router builds the stack Home, then Book 42, because the book route is a child of '/'. pop() removes Book 42, so Home is visible. With push('/books/42'), the new page is added on top of the existing Home page, so the stack is Home, Book 42, and pop() also returns to Home. The results look the same here. They differ when the user starts somewhere else: go replaces the stack with the stack matched by the location, while push keeps every page already on the stack.
Exercise
A teammate writes the child route as GoRoute(path: '/books/:id', ...) inside the routes list of the '/' route. What happens, and how do you fix it?
Show answer
go_router asserts when the router is created, because child route paths must not start with '/'. Change the path to 'books/:id'. Its full path is still '/books/:id'.