Sub topic 6
Building routes dynamically with `onGenerateRoute`
Assume you know Dart async and await, basic Flutter widgets, BuildContext, and how to run a Flutter app. This chapter focuses on named routes whose destination and data are selected at runtime.
Why use `onGenerateRoute`?
A route is an object that describes a screen transition. With onGenerateRoute, Flutter calls one function whenever the app needs a named route. The function receives a RouteSettings object containing:
name, such as/productsarguments, an optional value passed by the caller
The function can then choose the screen, validate its arguments, and create a MaterialPageRoute.
This keeps route construction in one place instead of spreading route logic across many widgets.
Define routes in one place
The following app opens a product screen from a home screen. The route factory checks that the product ID is an int before constructing ProductScreen.
import 'package:flutter/material.dart';
void main() {
runApp(const StoreApp());
}
class StoreApp extends StatelessWidget {
const StoreApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: '/',
onGenerateRoute: (settings) {
switch (settings.name) {
case '/':
return MaterialPageRoute<void>(
builder: (_) => const HomeScreen(),
settings: settings,
);
case '/product':
final argument = settings.arguments;
if (argument is! int) {
return MaterialPageRoute<void>(
builder: (_) => const ErrorScreen(
message: 'A numeric product ID is required.',
),
settings: settings,
);
}
return MaterialPageRoute<void>(
builder: (_) => ProductScreen(id: argument),
settings: settings,
);
}
return MaterialPageRoute<void>(
builder: (_) => const ErrorScreen(
message: 'Page not found.',
),
settings: settings,
);
},
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Store')),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.of(context).pushNamed(
'/product',
arguments: 42,
);
},
child: const Text('Open product 42'),
),
),
);
}
}
class ProductScreen extends StatelessWidget {
const ProductScreen({required this.id, super.key});
final int id;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Product')),
body: Center(child: Text('Product ID: $id')),
);
}
}
class ErrorScreen extends StatelessWidget {
const ErrorScreen({required this.message, super.key});
final String message;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Navigation error')),
body: Center(child: Text(message)),
);
}
}The settings: settings assignment preserves the route name and arguments on the created route. This helps route observers and debugging tools identify the route.
When this approach fits
onGenerateRoute works well for a small or medium app that uses imperative navigation with pushNamed. It also supports centralized validation and dependency construction.
It becomes less convenient when the app needs browser URLs, deep links, authentication redirects, or several persistent navigation branches. Those requirements usually favor declarative routing with Router or a package such as go_router.
| Need | `onGenerateRoute` fit |
|---|---|
| Central route mapping and typed checks | Good |
| Simple named navigation | Good |
| URL-driven deep links and nested navigation | Often limited |
Exercise
What should onGenerateRoute do when /product receives a value that is not an integer?
Show answer
It should avoid a forced cast and return an error route, or otherwise handle the invalid input safely.