Sub topic 3
Defining routes and paths
This chapter covers how a GoRoute describes a location. It covers the path syntax, how go_router matches a URL against your route list, and the rules that cause most startup errors. It assumes you can already create a GoRouter and pass it to MaterialApp.router, as the previous chapter showed.
What a GoRoute is
A GoRoute pairs a path pattern with a function that builds the screen for that pattern. The router holds a list of GoRoute objects. When the app needs to show a location such as /books/42, the router looks for a route whose pattern matches it, calls that route's builder, and shows the result.
These are the GoRoute parameters you will use most:
| Parameter | Purpose |
|---|---|
| `path` | The URL pattern, for example `/books/:id`. Required. |
| `builder` | Returns the widget for the screen. |
| `pageBuilder` | Returns a `Page` instead, for custom transitions. Use it in place of `builder`. |
| `name` | An optional unique name, used with `goNamed`. |
| `routes` | Child routes, nested under this one. |
| `redirect` | Sends the user elsewhere before the route builds. |
| `caseSensitive` | Whether `/Books` and `/books` differ. Defaults to `true`. |
Every GoRoute needs at least one of builder, pageBuilder, or redirect. If you provide none, go_router fails an assertion when the router is created.
A flat route table
The simplest table is a flat list. Each entry is a top-level route, and each path starts with /.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GoRouter router = GoRouter(
initialLocation: '/',
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
),
GoRoute(
path: '/books',
builder: (context, state) => const BookListScreen(),
),
GoRoute(
path: '/books/:id',
builder: (context, state) {
final String id = state.pathParameters['id']!;
final String? ref = state.uri.queryParameters['ref'];
return BookScreen(id: id, ref: ref);
},
),
],
);
void main() => runApp(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('/books'),
child: const Text('Browse books'),
),
),
);
}
}
class BookListScreen extends StatelessWidget {
const BookListScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Books')),
body: Center(
child: ElevatedButton(
onPressed: () => context.go('/books/42?ref=list'),
child: const Text('Open book 42'),
),
),
);
}
}
class BookScreen extends StatelessWidget {
const BookScreen({super.key, required this.id, this.ref});
final String id;
final String? ref;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Book $id')),
body: Center(child: Text('Opened from: ${ref ?? 'nowhere'}')),
);
}
}The builder receives a GoRouterState. These are its most useful properties for this chapter:
state.pathParametersis aMap<String, String>holding the values captured by:namesegments.state.uriis the full parsedUri. Query parameters live instate.uri.queryParameters.state.matchedLocationis the part of the location this route matched, with the parameters filled in.state.fullPathis the pattern of the matched route, such as/books/:id.
How paths are written
A path is a sequence of segments separated by /. A segment is either literal text or a parameter.
- A literal segment such as
booksmatches only that text. - A parameter segment such as
:idmatches one non-empty segment and stores it under the nameid. - A parameter never spans a slash.
/books/:idmatches/books/42but not/books/42/extra. - Path parameters are always strings. Parse them yourself with
int.tryParsewhen you need a number. - Query strings such as
?ref=listare not part of the path pattern. You never declare them, and they never affect matching.
Top-level and sub-route path rules
go_router enforces different rules depending on where a route sits. Breaking them produces an assertion error when the router is built.
- A top-level route must start with
/. - A sub-route, one listed in another route's
routes, must not start with/. - A sub-route path must not end with
/.
The full location of a sub-route is its parent's path joined to its own. This declaration produces the location /books/:id:
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GoRoute booksRoute = GoRoute(
path: '/books',
builder: (context, state) => const Text('Books'),
routes: <RouteBase>[
GoRoute(
// Correct: relative, no leading slash.
path: ':id',
builder: (context, state) => Text('Book ${state.pathParameters['id']}'),
),
// Wrong: GoRoute(path: '/:id', ...) fails the sub-route assertion.
],
);Nesting changes more than the URL. A matched sub-route is shown on top of its parent's page, so the user gets a back button that returns to the parent. A flat /books/:id route shows a single page with nothing beneath it. The next chapters cover navigation and the back stack in detail. For now, remember that nesting is a decision about the page stack, not only about paths.
How the router matches a location
go_router checks routes in the order you list them and descends into children. It stops at the first route chain that consumes the whole location.
Two consequences follow from this:
- A literal route must come before a parameter route that would also match it. If
/books/:idis listed above/books/new, the parameter route capturesnewas an id. Put/books/newfirst. - A location that no chain can consume completely is an error, even if a prefix matched.
/books/42/extrafails against the table above because nothing handles/extra. The router then shows the error page, which the error handling chapter covers.
Common mistakes
- Leading slash on a sub-route. It fails an assertion at startup, which is easy to spot.
- Forgetting that parameters are strings. The code compiles, then crashes at runtime on malformed URLs.
- Declaring query parameters in the path. Writing
/books?ref=:refdoes not work. Read queries fromstate.uri.queryParameters. - Relying on case-insensitive matching. With the default
caseSensitive: true,/Booksdoes not match/books. SetcaseSensitive: falseon a route only if you must accept both. - Duplicate names. If you give routes
namevalues, each must be unique and non-empty. Names are covered in a later chapter.
Exercise
You declare these top-level routes in this order: GoRoute(path: '/books/:id', ...) and then GoRoute(path: '/books/new', ...). A user opens /books/new. Which screen appears, and how do you fix it?
Show answer
The /books/:id route appears, with id equal to 'new', because routes are tried in list order and the parameter pattern also matches. Fix it by listing /books/new before /books/:id.
Exercise
A sub-route is declared as GoRoute(path: '/details', ...) inside the routes list of GoRoute(path: '/books', ...). What happens, and what is the corrected path?
Show answer
go_router fails an assertion when the router is created, because sub-route paths must not start with /. The corrected path is 'details', which yields the full location /books/details.