Sub topic 8
Home screen and named routes
This chapter covers how MaterialApp decides which screen to show first, and how it moves between screens by name. It assumes you can read basic Dart (classes, constructors, named parameters) and run a Flutter app. It also assumes you know what a StatelessWidget and its build method are. Earlier chapters built the MaterialApp, Scaffold and AppBar skeleton. Here you add a second screen and the routing that connects the two.
Two ways to pick the first screen
MaterialApp can start your app on a screen in two ways.
- The
homeproperty takes a widget. It is the shortest option and works well for a one-screen app. - The
routestable maps string names (paths) to widget builders.initialRoutesays which name to show first.
The simplest form is home:
MaterialApp(
title: 'Demo',
home: const HomePage(),
)Internally, MaterialApp builds a Navigator widget, the object that manages a stack of screens. Each screen on that stack is a Route. When you set home, the app registers it as the route named /, which is the default initial route name.
Now the same app with named routes:
MaterialApp(
title: 'Demo',
initialRoute: '/',
routes: {
'/': (context) => const HomePage(),
'/settings': (context) => const SettingsPage(),
},
)Each value in the map is a function that receives a BuildContext and returns the screen widget. The function runs each time the route is pushed, so the screen is built fresh on every navigation.
Do not use both for "/"
If you set home and also put a '/' key in routes, Flutter fails an assertion in debug mode. The two options would define the same route name twice. Choose one:
- Use
homefor the first screen androutesonly for the other screens. - Or leave
homeout and define'/'inroutes.
The second style keeps every screen in one table, so the rest of this chapter uses it.
Keeping route names in one place
Route names are plain strings. A typo such as '/setings' compiles, and only fails when the user taps the button. A small class of constants removes that risk:
class AppRoutes {
static const home = '/';
static const settings = '/settings';
static const detail = '/detail';
}The rest of the code refers to AppRoutes.settings and never repeats the string. The class can later move to its own file (see the chapter on organizing an app into files).
Pushing and popping by name
Two Navigator methods do most of the work:
Navigator.pushNamed(context, name)looks upnameand puts the new screen on top of the stack.Navigator.pop(context)removes the top screen and reveals the one below.
Here is a complete runnable app with a home screen, a settings screen and a detail screen:
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class AppRoutes {
static const home = '/';
static const settings = '/settings';
static const detail = '/detail';
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Routes demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
useMaterial3: true,
),
initialRoute: AppRoutes.home,
routes: {
AppRoutes.home: (context) => const HomePage(),
AppRoutes.settings: (context) => const SettingsPage(),
AppRoutes.detail: (context) => const DetailPage(),
},
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Inbox'),
actions: [
IconButton(
icon: const Icon(Icons.settings),
tooltip: 'Settings',
onPressed: () => Navigator.pushNamed(context, AppRoutes.settings),
),
],
),
body: ListView.builder(
itemCount: 5,
itemBuilder: (context, index) {
final title = 'Message ${index + 1}';
return ListTile(
title: Text(title),
onTap: () => Navigator.pushNamed(
context,
AppRoutes.detail,
arguments: title,
),
);
},
),
);
}
}
class SettingsPage extends StatelessWidget {
const SettingsPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Settings')),
body: const Center(child: Text('Settings go here')),
);
}
}
class DetailPage extends StatelessWidget {
const DetailPage({super.key});
@override
Widget build(BuildContext context) {
final title = ModalRoute.of(context)!.settings.arguments as String;
return Scaffold(
appBar: AppBar(title: Text(title)),
body: Center(child: Text('Body of "$title"')),
);
}
}Run it and tap the gear icon. The settings screen slides in. Its AppBar shows a back arrow that you never wrote.
Why the back button appears
AppBar has a property called automaticallyImplyLeading, which defaults to true. When the leading slot is empty, the bar checks its situation and picks a widget:
- If the
Scaffoldhas adrawer, it shows a menu icon that opens the drawer. - Otherwise, if the current route can be popped (there is a screen below it on the stack), it shows a
BackButton. - Otherwise it shows nothing.
The home screen is the bottom of the stack, so it has no back button. Anything pushed on top does. If you supply your own leading widget, this logic is skipped. Setting automaticallyImplyLeading: false removes the automatic widget without adding another.
The system back gesture and the Android back button also pop the stack. They work with no code from you.
Passing data with arguments
pushNamed takes an optional arguments parameter of type Object?. The destination reads it from its route settings:
final title = ModalRoute.of(context)!.settings.arguments as String;ModalRoute.of(context) finds the route that is showing this screen. The ! asserts it exists, and the as String cast asserts the caller passed the right type. Neither is checked at compile time. If a caller forgets the argument, the app throws a null error at runtime.
Because of this, make the contract explicit. A common approach is a small class:
class DetailArgs {
const DetailArgs({required this.id, required this.title});
final int id;
final String title;
}The caller passes DetailArgs(id: 3, title: 'Message 3'), and the screen casts to DetailArgs. A cast still happens, but it now lives in one place.
Reading arguments in `onGenerateRoute`
The routes table builders cannot see the arguments directly. If you want the screen to take its data as a constructor parameter, use onGenerateRoute, which receives the full RouteSettings:
MaterialApp(
initialRoute: AppRoutes.home,
onGenerateRoute: (settings) {
switch (settings.name) {
case AppRoutes.home:
return MaterialPageRoute(
builder: (_) => const HomePage(),
settings: settings,
);
case AppRoutes.detail:
final args = settings.arguments as DetailArgs;
return MaterialPageRoute(
builder: (_) => DetailPage(args: args),
settings: settings,
);
}
return null;
},
)Here DetailPage takes args in its constructor, so it no longer depends on ModalRoute. Passing settings: settings to MaterialPageRoute keeps the route name for tools such as observers. Returning null means "I don't handle this name" and moves on to the next fallback.
How a name is resolved
When you call pushNamed, the Navigator asks the app to turn the name into a route. The order is fixed:
The routes table wins whenever it has the name. onGenerateRoute only runs for names the table does not contain. Use onUnknownRoute as a "page not found" screen:
MaterialApp(
routes: {
AppRoutes.home: (context) => const HomePage(),
},
onUnknownRoute: (settings) => MaterialPageRoute(
builder: (_) => Scaffold(
appBar: AppBar(title: const Text('Not found')),
body: Center(child: Text('No route for ${settings.name}')),
),
),
)Getting a result back
pushNamed returns a Future that completes when the pushed screen is popped. The value passed to pop becomes the result:
Future<void> _openSettings(BuildContext context) async {
final saved = await Navigator.pushNamed<bool>(context, AppRoutes.settings);
if (!context.mounted) return;
if (saved == true) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Settings saved')),
);
}
}The settings screen answers with Navigator.pop(context, true). If the user uses the back arrow instead, the result is null, so always handle null. The context.mounted check matters because the widget may have left the tree while you waited. Using a BuildContext after an await without that check is a common lint warning and a real source of crashes.
Other Navigator methods
| Method | Effect on the stack | Typical use |
|---|---|---|
| `pushNamed` | Adds a screen on top | Open a detail or settings screen |
| `pop` | Removes the top screen | Close a screen, return a result |
| `pushReplacementNamed` | Replaces the top screen with a new one | Move from a login screen to the home screen |
| `pushNamedAndRemoveUntil` | Pushes, then removes screens until a test returns true | Log out and return to the start |
| `popUntil` | Pops screens until a test returns true | Return to the home screen from a deep flow |
| `maybePop` | Pops only if the route allows it | Respect a `PopScope` that blocks leaving |
For example, to go to the home screen and clear everything above it:
Navigator.pushNamedAndRemoveUntil(
context,
AppRoutes.home,
(route) => false,
);The test (route) => false removes every earlier route, so the home screen becomes the only one. With ModalRoute.withName(AppRoutes.home) as the test, the routes below the home screen are kept.
Common errors
- "Navigator operation requested with a context that does not include a Navigator." The
contextyou passed sits aboveMaterialApp, so theNavigatoris not an ancestor. This happens when you callNavigator.of(context)in the samebuildmethod that creates theMaterialApp. Move the button into a separate widget belowMaterialApp, asHomePageis above, or use aBuilder. - "Could not find a generator for route RouteSettings("/x")". The name is not in
routes, and neitheronGenerateRoutenoronUnknownRoutereturned a route. Check for a typo or add a fallback. - Assertion about
homeand'/'. You defined the root route twice. Remove one. - Null check error on
arguments. The screen was pushed without the argument it expects, often from a second call site added later.
Summary of the working model
MaterialAppowns oneNavigator. TheNavigatorholds a stack of routes.homeis shorthand for the route named/. Do not define/twice.routesmaps names to builders.initialRoutepicks the starting name.pushNamedadds to the stack,popremoves from it, and both can carry data.- Each screen has its own
ScaffoldandAppBar.AppBaradds a back button on its own when the route can be popped.
Exercise
Your app has home: const HomePage() and a routes map that also contains '/': (context) => const HomePage(). What happens in debug mode, and how do you fix it?
Show answer
Flutter fails an assertion because the root route / is defined twice, once through home and once through routes. Fix it by removing one of them. Either delete the '/' entry and keep home, or delete home and keep '/' in routes.
Exercise
A DetailPage is pushed with Navigator.pushNamed(context, '/detail'), but it crashes with a null check error on ModalRoute.of(context)!.settings.arguments as String. Why does it crash, and what are two ways to make the code safer?
Show answer
The caller did not pass arguments, so the value is null and the cast to String fails. Two fixes: pass the argument at every call site and wrap the data in a small class (such as DetailArgs) so the contract is explicit, or use onGenerateRoute to read settings.arguments once and give DetailPage a required constructor parameter, so a missing value is caught in one place.
Exercise
A user taps "Settings" on the home screen, then taps the back arrow without saving. What does await Navigator.pushNamed<bool>(context, '/settings') return, and what check should come before using context afterward?
Show answer
It returns null, because the screen was popped with no result value. Check context.mounted after the await before using context, and treat null as "nothing was saved".