Sub topic 5
Named Routes and When They Fall Short
Prerequisites
You should know Dart’s basic syntax, async and await, Flutter widgets such as Scaffold and AppBar, and how BuildContext connects a widget to the surrounding application.
Defining named routes
A named route is a screen identified by a string such as / or /details. You register route names in MaterialApp, then navigate with pushNamed.
The routes property is a map from route names to functions that build screens:
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(),
'/details': (context) => const DetailsScreen(),
},
);
}
}
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(
'/details',
arguments: 42,
);
},
child: const Text('Open product'),
),
),
);
}
}
class DetailsScreen extends StatelessWidget {
const DetailsScreen({super.key});
@override
Widget build(BuildContext context) {
final productId =
ModalRoute.of(context)?.settings.arguments as int?;
return Scaffold(
appBar: AppBar(title: const Text('Details')),
body: Center(
child: Text('Product ID: ${productId ?? 'missing'}'),
),
);
}
}pushNamed adds the route to the Navigator stack. The arguments value travels through the route settings. The destination reads it with ModalRoute.of(context).
The route table can make small applications easy to understand:
| Feature | Named route behavior |
|---|---|
| Register a screen | Add an entry to `routes` |
| Navigate | Call `pushNamed('/details')` |
| Pass data | Use the `arguments` parameter |
| Return to the previous screen | Call `Navigator.pop(context)` |
Where named routes fall short
Named routes use untyped strings. A spelling mistake such as /detail instead of /details is discovered at runtime. The compiler cannot check that the name exists.
Arguments are also untyped. The destination must cast settings.arguments, so a caller could pass the wrong type. Large applications can accumulate route names, argument conventions, and validation code in different files.
The routes map is limited when a route needs different construction logic. For example, a product screen might need to validate an ID, load a dependency, or choose between several screens. In that situation, use onGenerateRoute to centralize route creation:
MaterialApp(
onGenerateRoute: (settings) {
if (settings.name == '/details') {
final id = settings.arguments as int;
return MaterialPageRoute<void>(
builder: (_) => DetailsScreen(productId: id),
settings: settings,
);
}
return MaterialPageRoute<void>(
builder: (_) => const HomeScreen(),
settings: settings,
);
},
);Constructor parameters are usually clearer and safer inside the application. Named routes remain useful for simple route tables and compatibility with older navigation code. For deep links, authentication redirects, browser URLs, and nested navigation, declarative routing packages such as go_router provide a better model.
Exercise
Why can a named route with arguments fail even when the route name is correct?
Show answer
The caller can pass an unexpected argument type, or omit the argument. Validate and cast the value at the route boundary, or prefer a typed constructor when practical.