Declarative Navigation: Navigator 2.0
Learn to use Flutter’s Navigator 2.0 in your app.
To better understand Navigator 2.0, we will work on a simplified version of the shop app. At the end of this lesson, we will learn how to:
- Use
pages
to populate a list of pages in the navigation stack. - Use the
Router
API to handle routes from the operating system.
Getting started
We will work on the app below. Take a look at it and run it:
import 'package:flutter/material.dart'; import 'presentation/item_list_screen.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, useMaterial3: false, ), home: const ItemListScreen(), ); } }
It contains the following screens:
Only the “Item List” screen is visible. We will be able to navigate to the remaining screens at the end of this lesson.
Working with pages
Navigator has a pages
property that lets us manage the list of pages in the navigation stack. To demonstrate how this works, we will navigate back and forth between the item list, item detail, and error pages.
1. Adding Navigator
to MaterialApp
We will need to add the Navigator
widget to our MaterialApp
in the lib/main.dart
file. We will also need to add the pages
and onPopPage
properties.
import 'package:flutter/material.dart';void main() {runApp(const MyApp());}class MyApp extends StatelessWidget {const MyApp({Key? key}) : super(key: key);@overrideWidget build(BuildContext context) {return MaterialApp(title: 'Flutter Demo',theme: ThemeData(primarySwatch: Colors.blue,),// Navigator addedhome: Navigator(pages: [],onPopPage: (route, result) => route.didPop(result),),);}}
The onPopPage
is required to clean up the navigation stack.
2. Adding ItemListScreen
to the navigation stack
The pages
property in lib/main.dart
takes in a list of pages.
Note: Include the imports added in the code ...