Sub topic 16
Type-safe routes with go_router_builder
This chapter assumes you can configure a GoRouter, define nested GoRoutes with path and query parameters, and navigate with go and push. You should also know how to run a Dart command-line tool. Earlier chapters used string paths such as '/books/42'. This chapter replaces those strings with generated, compiler-checked classes.
Why strings are a weak spot
String-based navigation breaks quietly. You can mistype '/book/42', forget to encode a query value, or pass 'abc' where the screen expects an int. None of these fail at compile time. They surface as a 404 screen or a parsing exception at runtime.
go_router_builder is a code generator. You describe each route as an annotated class. The generator writes the GoRoute tree, the parameter parsing, and the navigation methods. A wrong parameter name or type becomes a build error or a compile error.
Installing the generator
The generator runs at development time only, so it goes in dev_dependencies.
dependencies:
flutter:
sdk: flutter
go_router: ^14.0.0
dev_dependencies:
build_runner: ^2.4.0
go_router_builder: ^2.7.0Use the current versions from pub.dev. go_router_builder must be compatible with your go_router version.
Generate code with:
dart run build_runner build --delete-conflicting-outputsDuring development, use dart run build_runner watch to regenerate on every save.
Declaring typed routes
Each route is a class that extends GoRouteData. The @TypedGoRoute annotation on the top-level class declares the path and any child routes. The class also mixes in a generated mixin that adds go, push, and location.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
part 'routes.g.dart';
@TypedGoRoute<HomeRoute>(
path: '/',
routes: <TypedGoRoute<GoRouteData>>[
TypedGoRoute<BookRoute>(path: 'books/:id'),
],
)
class HomeRoute extends GoRouteData with $HomeRoute {
const HomeRoute();
@override
Widget build(BuildContext context, GoRouterState state) =>
const HomeScreen();
}
class BookRoute extends GoRouteData with $BookRoute {
const BookRoute({required this.id, this.ref});
final int id;
final String? ref;
@override
Widget build(BuildContext context, GoRouterState state) =>
BookScreen(id: id, ref: ref);
}
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: () => BookRoute(id: 42, ref: 'home').go(context),
child: const Text('Open book 42'),
),
),
);
}
}
class BookScreen extends StatelessWidget {
const BookScreen({super.key, required this.id, this.ref});
final int 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'}')),
);
}
}After running the generator, routes.g.dart exists. It contains a $appRoutes list, which you pass to the router.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'routes.dart';
final GoRouter router = GoRouter(
initialLocation: '/',
routes: $appRoutes,
);
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(routerConfig: router);
}
}$appRoutes is declared in routes.g.dart, so import routes.dart and not the generated file directly.
How the generator reads your classes
The generator maps constructor parameters to URL parts using three rules.
| Constructor parameter | Becomes | Example |
|---|---|---|
| Name matches a `:segment` in the path | Path parameter | `id` in `books/:id` |
| Any other named parameter | Query parameter | `ref` in `?ref=home` |
| A field named `$extra` | The `extra` object | `final Book $extra;` |
Parameter types are parsed for you. A field typed int is converted with an integer parse, so /books/abc fails to match instead of crashing inside your widget. String, int, double, bool, num, BigInt, DateTime, Uri, and enums are supported. Collections such as List<int> and Set<String> work as query parameters.
Default values keep URLs short. If a constructor declares this.page = 1 and a caller passes 1, the generated code leaves page out of the query string. A nullable query field that is null is omitted too.
The diagram below shows the flow from annotations to navigation calls.
Navigating with generated methods
The mixin exposes the same operations you used with strings.
import 'package:flutter/material.dart';
import 'routes.dart';
class TypedNavigationDemo extends StatelessWidget {
const TypedNavigationDemo({super.key});
@override
Widget build(BuildContext context) {
return Column(
children: [
TextButton(
onPressed: () => BookRoute(id: 42).go(context),
child: const Text('go'),
),
TextButton(
onPressed: () => BookRoute(id: 42, ref: 'demo').push(context),
child: const Text('push'),
),
TextButton(
onPressed: () => const HomeRoute().replace(context),
child: const Text('replace'),
),
Text(BookRoute(id: 42, ref: 'demo').location),
],
);
}
}The last line prints /books/42?ref=demo. The location getter is useful for links, logging, and tests, because it builds the encoded URL without navigating. The semantics of go, push, and replace are the same as before: go rebuilds the stack for the location, and push adds a page on top.
Overriding redirects and pages in a route class
GoRouteData has overridable methods that mirror GoRoute arguments. A route class can guard itself or supply its own transition without leaving the typed approach.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
part 'admin_routes.g.dart';
@TypedGoRoute<AdminRoute>(path: '/admin')
class AdminRoute extends GoRouteData with $AdminRoute {
const AdminRoute();
@override
String? redirect(BuildContext context, GoRouterState state) {
const bool isAdmin = false; // Replace with a real auth check.
return isAdmin ? null : '/';
}
@override
CustomTransitionPage<void> buildPage(
BuildContext context,
GoRouterState state,
) {
return CustomTransitionPage<void>(
key: state.pageKey,
child: const Scaffold(body: Center(child: Text('Admin'))),
transitionsBuilder: (context, animation, secondaryAnimation, child) =>
FadeTransition(opacity: animation, child: child),
);
}
}If you override buildPage, the generator does not need build. Override one or the other. Shell layouts have typed equivalents, TypedShellRoute and TypedStatefulShellRoute, which pair with ShellRouteData and StatefulShellRouteData classes.
Common errors
- Missing part directive. Without
part 'routes.g.dart';, the generated code is not linked to your library, and$appRoutesis undefined. - Stale generated file. After you rename a field or change a path, run the build again. An old
.g.dartfile produces confusing type errors. - Mismatched path parameter. If the path says
:bookIdand the constructor field isid, the generator treatsidas a query parameter and complains thatbookIdhas no field. - Unsupported field types. Arbitrary objects cannot be encoded in a URL. Use
$extrafor those, with the same limits as plainextra: it is lost on a browser refresh and on deep links. - Wrong constructor. The route class needs a constructor that the generator can call with every path and query field. Required path fields must be
requiredor positional.
Trade-offs
Generated routes add a build step, a second file per library, and a dependency on build_runner. In return you get parameter parsing in one place, refactor-safe navigation calls, and errors at build time. For small apps with a handful of screens, plain GoRoutes are often enough. For apps with many parameterized routes, the typed approach pays for itself, because renaming a parameter shows every broken call site at once.
Exercise
A route is declared as TypedGoRoute<ProductRoute>(path: 'products/:sku'), and the class has const ProductRoute({required this.sku, this.color, this.page = 1}); with fields String sku, String? color, and int page. What does ProductRoute(sku: 'A1', color: 'red', page: 1).location return, and which fields are path or query parameters?
Show answer
It returns /products/A1?color=red, with the parent path prefix included if the route is nested under /. sku is the path parameter because its name matches :sku. color and page are query parameters. page is omitted because its value equals the default of 1.
Exercise
You rename the id field of BookRoute to bookId but forget to update the path books/:id and do not rerun build_runner. What goes wrong, and how do you fix it?
Show answer
The old generated file still refers to id, so the project fails to compile or the route does not match. Change the path to books/:bookId so the name matches the field, then rerun dart run build_runner build --delete-conflicting-outputs. The generator then reports any remaining mismatch at build time.