Sub topic 3
Home screen and named routes
This chapter assumes you have a Flutter app that runs, that you know Dart classes and named parameters, and that you can write a StatelessWidget with a build method. You have seen MaterialApp, Scaffold, and AppBar before.
Home screen and named routes
MaterialApp takes a routes map. Each key is a path string, and each value builds a screen. initialRoute picks the screen shown first.
MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => const HomePage(),
'/settings': (context) => const SettingsPage(),
},
)Call Navigator.pushNamed(context, '/settings') to open a screen. Flutter adds a back button to the AppBar of any screen pushed this way.
Adding a Drawer
A Drawer is a side menu that slides in from the left. Give it to the Scaffold, and the AppBar shows a menu icon automatically. Close the drawer with Navigator.pop before you navigate, or the drawer stays open on the new screen.
Scaffold(
appBar: AppBar(title: const Text('Home')),
drawer: Drawer(
child: ListView(
children: [
ListTile(
leading: const Icon(Icons.settings),
title: const Text('Settings'),
onTap: () {
Navigator.pop(context);
Navigator.pushNamed(context, '/settings');
},
),
],
),
),
body: const Center(child: Text('Swipe from the left edge')),
)Showing SnackBars with ScaffoldMessenger
A SnackBar is a short message at the bottom of the screen. ScaffoldMessenger.of(context) finds the messenger that MaterialApp provides, so the call works from any widget below the app root.
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Message saved')),
);Organizing your app into widgets and files
Put main() and MaterialApp in main.dart. Put each screen in its own file, and move widgets used by several screens into a shared folder.
| File | Contains |
|---|---|
| `lib/main.dart` | `main()`, `MaterialApp`, routes |
| `lib/screens/home_page.dart` | `HomePage` |
| `lib/widgets/app_drawer.dart` | Shared `AppDrawer` |
Collapsing app bars with SliverAppBar
SliverAppBar scrolls with the content. Place it inside a CustomScrollView in the Scaffold body. With floating: true, the bar reappears as soon as the user scrolls up.
Scaffold(
body: CustomScrollView(
slivers: [
const SliverAppBar(title: Text('Feed'), floating: true),
SliverList.builder(
itemCount: 30,
itemBuilder: (context, index) => ListTile(title: Text('Item $index')),
),
],
),
)Exercise
A drawer item calls Navigator.pushNamed without calling Navigator.pop first. What does the user see after tapping it?
Show answer
The new screen opens, but the drawer stays open on top of it, so the user must close it manually. Calling Navigator.pop first closes the drawer before the push.