Sub topic 6
Building routes dynamically with onGenerateRoute
This chapter assumes you can push and pop routes, know that Navigator.pushNamed takes a route name and optional arguments, and have registered a static routes table in MaterialApp. It covers what to do when that table is not enough.
Why a static routes table falls short
A routes map pairs each name with a builder, for example '/settings': (context) => const SettingsScreen(). That works for fixed screens. It breaks down in three cases:
- The name carries data, such as
/products/42. You cannot register every possible id. - The screen needs typed arguments, and you want to validate them in one place instead of in every builder.
- You want one fallback for names nobody handles.
onGenerateRoute solves these. It is a function that receives a RouteSettings (the route's name and arguments) and returns a Route, or null if it does not recognize the name.
How Flutter resolves a name
When you call pushNamed, MaterialApp looks for a route in a fixed order.
Two consequences follow from this order:
- The
routestable always wins. If'/'is in the table,onGenerateRouteis never asked about it. - If you set
home, the name'/'is already taken. Do not also handle'/'inonGenerateRoute.
A complete example
The following program handles /, /products/<id> with an optional ?ref= query, and everything else through a fallback page.
import 'package:flutter/material.dart';
void main() => runApp(const ShopApp());
MaterialPageRoute<void> _page(RouteSettings settings, Widget child) {
return MaterialPageRoute<void>(
settings: settings,
builder: (_) => child,
);
}
Route<dynamic>? generateRoute(RouteSettings settings) {
final uri = Uri.parse(settings.name ?? '/');
final segments = uri.pathSegments;
if (segments.isEmpty) {
return _page(settings, const HomeScreen());
}
if (segments.length == 2 && segments[0] == 'products') {
final id = int.tryParse(segments[1]);
if (id == null) return null; // falls through to onUnknownRoute
return _page(
settings,
ProductScreen(id: id, source: uri.queryParameters['ref']),
);
}
return null;
}
class ShopApp extends StatelessWidget {
const ShopApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: '/',
onGenerateRoute: generateRoute,
onUnknownRoute: (settings) => _page(
settings,
NotFoundScreen(name: settings.name),
),
);
}
}
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: () => Navigator.of(context)
.pushNamed('/products/42?ref=home'),
child: const Text('Product 42'),
),
ElevatedButton(
onPressed: () =>
Navigator.of(context).pushNamed('/products/abc'),
child: const Text('Broken link'),
),
],
),
),
);
}
}
class ProductScreen extends StatelessWidget {
const ProductScreen({super.key, required this.id, this.source});
final int id;
final String? source;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Product $id')),
body: Center(child: Text('Opened from: ${source ?? 'unknown'}')),
);
}
}
class NotFoundScreen extends StatelessWidget {
const NotFoundScreen({super.key, this.name});
final String? name;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Not found')),
body: Center(child: Text('No screen for ${name ?? 'null'}')),
);
}
}Points worth noticing:
RouteSettings.nameholds the whole string, including the query.Uri.parsesplits it intopathSegmentsandqueryParameters, so you do not write your own parser.- Each route receives
settings: settings. Without it, the route has no name.ModalRoute.of(context)?.settings.namethen returnsnull, and anyNavigatorObserversees unnamed routes. '/products/abc'failsint.tryParse, so the generator returnsnull. This sends the request toonUnknownRouteinstead of crashing.
Passing typed arguments
The name is a string, but arguments is an Object?. For data that does not belong in a URL, define a small class and check its type in the generator.
import 'package:flutter/material.dart';
class CheckoutArgs {
const CheckoutArgs({required this.productId, required this.quantity});
final int productId;
final int quantity;
}
class CheckoutScreen extends StatelessWidget {
const CheckoutScreen({super.key, required this.args});
final CheckoutArgs args;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Checkout')),
body: Center(
child: Text('${args.quantity} x product ${args.productId}'),
),
);
}
}
Route<dynamic>? generateCheckout(RouteSettings settings) {
if (settings.name == '/checkout') {
final args = settings.arguments;
if (args is CheckoutArgs) {
return MaterialPageRoute<void>(
settings: settings,
builder: (_) => CheckoutScreen(args: args),
);
}
}
return null;
}
// Caller:
// Navigator.of(context).pushNamed(
// '/checkout',
// arguments: const CheckoutArgs(productId: 42, quantity: 2),
// );Use args is CheckoutArgs instead of settings.arguments as CheckoutArgs. The cast throws a TypeError when a caller forgets the argument, while the type check lets the generator return null and show your fallback page.
Gotchas and edge cases
Initial routes with several segments
If initialRoute is /products/42, Flutter does not build only that route. It asks the generator for each prefix (/, /products, then /products/42) and stacks the ones that resolve. Arguments are null for all of them. Your generator must therefore return null for names it does not know, such as /products. Do not throw. If the final route does not resolve, Flutter discards the whole stack and falls back to /.
Arguments do not survive a reload
On the web, the browser URL stores only the name. A page reload rebuilds the route from the name with arguments set to null. Anything the screen needs after a reload must therefore be in the path or query, as id is in the example above. Keep arguments for data that is acceptable to lose.
A growing switch
Every new screen adds a branch to one function, and string matching has no compile-time checking. Common mitigations are constants for names, a small AppRoutes class that holds the generator, and parsing helpers per route. If you find yourself writing a path-pattern matcher with parameters, you are rebuilding what go_router provides, which later chapters cover.
Navigator 1.0 only
onGenerateRoute belongs to the imperative Navigator API. The route stack is changed by calls such as pushNamed, and the URL on the web is a side effect. It does not give you a single source of truth for "where is the app now", and that limit motivates declarative routing.
Quick reference
| Concern | Where to handle it |
|---|---|
| Fixed screens without data | `routes` table |
| Data in the path or query | `onGenerateRoute` with `Uri.parse` |
| Non-URL data | Typed `arguments`, checked with `is` |
| Unrecognized or malformed names | Return `null`, then `onUnknownRoute` |
| Route name visible to observers | Pass `settings: settings` to the route |
Exercise
A user taps Navigator.of(context).pushNamed('/products/7'). The routes table contains '/products/7': (_) => const SpecialOffer(), and onGenerateRoute would also match this name and build ProductScreen(id: 7). Which screen opens, and why? Then explain what happens for '/products/seven' with the generator from this chapter.
Show answer
SpecialOffer opens, because the routes table is checked before onGenerateRoute, and a match there ends the lookup. For '/products/seven', int.tryParse('seven') returns null, so the generator returns null. Flutter then calls onUnknownRoute, which shows NotFoundScreen with the name /products/seven.