Sub topic 5
Named routes and when they fall short
This chapter assumes you can push and pop routes with Navigator, pass data through constructors, and read async and await code. It covers Flutter's named routes, the errors they usually cause, and the point where you should stop using them.
What a named route is
A named route is a route you reach by a string, such as '/details', instead of by building a MaterialPageRoute at the call site. You register names with the app, and you call Navigator.pushNamed with a name. The call site no longer needs to import or construct the destination widget.
Flutter gives you two places to register names:
- The
routesmap onMaterialApp, which links each name to a widget builder. - The
onGenerateRoutecallback, which builds a route from a name and its arguments. The next chapter covers it.
Registering routes with the routes table
The routes parameter is a Map<String, WidgetBuilder>. The initialRoute parameter says which name to show first.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => const HomeScreen(),
'/settings': (context) => const SettingsScreen(),
},
);
}
}
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: () => Navigator.of(context).pushNamed('/settings'),
child: const Text('Open settings'),
),
),
);
}
}
class SettingsScreen extends StatelessWidget {
const SettingsScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Settings')),
body: Center(
child: ElevatedButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Back'),
),
),
);
}
}pushNamed does the same job as push. It adds a route to the top of the stack, and pop removes it. Only the way you describe the destination changes.
MaterialApp has one special rule. If you set home, the app also registers '/', so you must not define '/' in routes at the same time. Doing both fails an assertion in debug mode. Pick one.
Passing arguments
pushNamed takes an optional arguments value of type Object?. The destination reads it from ModalRoute.of(context)!.settings.arguments.
// Caller
Navigator.of(context).pushNamed('/details', arguments: 42);
// Destination
class ProductScreen extends StatelessWidget {
const ProductScreen({super.key});
@override
Widget build(BuildContext context) {
final id = ModalRoute.of(context)!.settings.arguments as int;
return Scaffold(
appBar: AppBar(title: Text('Product $id')),
);
}
}This works, but it moves the contract between the two screens out of the type system. The screen no longer declares what it needs in its constructor. The compiler cannot check the caller, and the cast as int can fail at runtime.
A common fix is a small class that holds the arguments and a static helper that does the cast in one place:
class ProductArgs {
const ProductArgs({required this.id, required this.title});
final int id;
final String title;
}
// Caller
Navigator.of(context).pushNamed(
'/details',
arguments: const ProductArgs(id: 42, title: 'Lamp'),
);This helps readability, but a wrong type still fails at runtime and not at compile time.
Returning a result
Named pushes return a Future just as push does. The Future completes with the value passed to pop, or with null if the user leaves another way.
Future<void> chooseSize(BuildContext context) async {
final size = await Navigator.of(context).pushNamed<String>('/size-picker');
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Size: ${size ?? 'none'}')),
);
}The context.mounted check matters because the widget may have been removed while the user was on the other screen.
Related navigation methods
Named routes come with variants that change the stack in different ways.
| Method | Effect on the stack |
|---|---|
| `pushNamed` | Adds the route on top. |
| `pushReplacementNamed` | Removes the current route and adds the new one in its place. |
| `popAndPushNamed` | Pops the current route, then pushes the new one. |
| `pushNamedAndRemoveUntil` | Pushes the new route, then removes routes below it until a predicate returns true. |
| `restorablePushNamed` | Pushes the route and lets Flutter restore it after the app process is killed. |
A frequent pattern is returning to the start of the app after login or logout:
Navigator.of(context).pushNamedAndRemoveUntil(
'/',
(route) => false,
);The predicate (route) => false never stops, so every earlier route is removed and only '/' remains. To keep the first route, use ModalRoute.withName('/') as the predicate.
What happens with an unknown name
If a name is not in routes and there is no onGenerateRoute, Flutter calls onUnknownRoute. If that is also missing, a debug build throws an error. Provide a fallback so a typo does not crash the app in production:
MaterialApp(
routes: {
'/': (context) => const HomeScreen(),
},
onUnknownRoute: (settings) => MaterialPageRoute<void>(
builder: (_) => Scaffold(
body: Center(child: Text('No page for ${settings.name}')),
),
settings: settings,
),
);How a name is resolved
The diagram shows the order in which Flutter looks for a route when you call pushNamed.
Where named routes fall short
Named routes are fine for a small app with a few fixed screens. They show their limits as the app grows.
- Arguments are untyped. Data travels as
Object?, so mistakes surface at runtime. - Names are plain strings. A typo compiles. You can reduce the risk with constants, but nothing forces everyone to use them.
- No path parameters. A name like
'/products/42'is a literal key in the map. Theroutestable cannot match a pattern and extract42. You needonGenerateRouteand your own string parsing. - Deep links are weak. On the web, the browser URL can show the name, but the stack behind it is not described by the URL. A user who opens
/detailsdirectly has noHomescreen under it, and the app does not know how to rebuild a sensible history. - The stack is imperative. You change it by calling methods. The app cannot declare "the stack should be these three pages" and let Flutter reconcile it.
- Redirects need manual code. Guarding a screen behind login means checking state in each caller or inside the screen.
Flutter's own documentation recommends against named routes for most apps for these reasons, and points to a package such as go_router for apps that need deep links or the web.
Choosing between the approaches
| Situation | Reasonable choice |
|---|---|
| Prototype or a few screens, mobile only | `Navigator.push` with constructors |
| Small app, fixed screens, no deep links | Named routes with a `routes` table |
| Names needed but arguments are dynamic | `onGenerateRoute` |
| Web support, deep links, auth redirects, nested tabs | `go_router` |
Constructor-based push is often better than named routes even in small apps, because the compiler checks the arguments. Use names when you need to trigger navigation from a place that cannot import the destination, such as a notification handler.
Common errors
- Defining
'/'inrouteswhile also settinghome. Remove one of them. - Reading arguments in
initState.ModalRoute.of(context)depends on the inherited widget tree, so call it inbuildordidChangeDependencies. - Casting to the wrong type. If the caller sends a
Stringand the destination casts toint, you get aTypeErrorat runtime. Keep the caller and destination next to each other or share an arguments class. - Using
contextafter anawaitwithout checkingmounted. Checkcontext.mountedfirst. - Expecting the system back button to leave the app after
pushReplacementNamed. The replaced route is gone, so back goes to whatever was below it.
Summary of the working model
A named route is a string key that maps to a route-building function. pushNamed looks the key up, in order, in the routes table, onGenerateRoute, and onUnknownRoute, then pushes the result onto the same stack that push uses. Naming a route does not change how the stack works. It changes how you refer to the destination, and it gives up compile-time checks in exchange.
Exercise
A user taps a notification that carries the string '/products/42'. You register routes with only a routes table containing '/' and '/products'. What happens when you call pushNamed('/products/42'), and which mechanism should you add to handle it?
Show answer
The name '/products/42' is not a key in the routes table, because the table does exact string matching and cannot extract a parameter. Flutter then calls onGenerateRoute, and if that is not set it calls onUnknownRoute or throws in debug mode. Add an onGenerateRoute callback that parses the name (for example with Uri.parse, checking pathSegments), reads the id, and returns a MaterialPageRoute that builds the product screen with the id passed through its constructor. For apps that need many such patterns, go_router handles path parameters directly.
Exercise
Why does reading ModalRoute.of(context)!.settings.arguments inside initState cause problems, and where should you read it instead?
Show answer
ModalRoute.of(context) registers a dependency on an inherited widget, and Flutter does not allow that in initState because the element is not yet fully part of the tree. Read the arguments in build, or in didChangeDependencies if you need to run logic once per change.