Navigation and Routing
Navigation and Routing
In this chapter, we are going to explore how navigation and routing work in Flutter. We will explore Navigator 1.0, the simplest and most approachable method of routing (albeit with its own drawbacks and limitations), then we will investigate the newer and more powerful Navigator 2.0. Finally, we will explore a package that seeks to make Navigator 2.0 as easy to use as possible.
Example 8.1–Example 8.29 in the Chapter 08 folder; most examples are the whole program up to that point, so each code block below is labelled with the first example that contains it. Blocks without a label have no counterpart in the repository. The repository's constructors use the older {Key? key}) : super(key: key) form instead of {super.key}, and it has conversion glitches of its own, so the code on this page follows the book (BPB Publications, n.d.).Chapter overview
Structure
- A general discussion of navigation and routing concepts
- An introduction to Navigator 1.0
- Routing using named routes
- Passing arguments into a route
- Returning data from a screen
- Animating a widget from one route to another
- Introduction to Navigator 2.0 — the Router API
- Using packages to help with routing
Objectives
Runnable example
examples/flutter_for_jobseekers_ch08/. The code on this page is shown as the book prints it, with conversion glitches fixed.General discussion of navigation and routing concepts
As we briefly touched on in the introduction, applications respond to a user's intent to navigate by routing them to the place they would like to go. If you have ever clicked a link on a website, you will know exactly what this process looks like: you click a link, the browser thinks for a minute, the URL changes, then your new page loads. The browser manages your intent to navigate to the new page in the way of updating the URL that is currently being displayed, then displaying the page.
In an application, the mechanics can differ, but the overall process is remarkably similar. As a user, you tap on a cog wheel icon with the intent to access settings and the application routes you to the settings screen, very much like a Web page would work. In fact, if you will recall, Flutter itself was born out of the Web-world, so many of the concepts and paradigms are still closely related to its history with the Web.
Where Flutter differs from the Web
Where Flutter differs from the Web, however, is in how it manages the state objects of screens not currently in the foreground.
On the Web
Once you navigate away from a page, you lose the state of the elements on the page (unless the state has been written to a local cache, then injected back into the page when you navigate back to it, or the backend manages the state similarly).
This is the reason why your Web browser will ask you if you are quite certain that you would like to navigate away from a form once you have started to fill it out but have not yet submitted it: if you do, the state of the form will be lost, and you will have to start over if you navigate back to the page.
In Flutter
The navigation stack
It is this concept of a navigation stack that will help us to make sense of how routing works in applications:
The app launches
When an application launches, the first card in the stack is a loading screen.
The main screen replaces the loading screen
Once the application has loaded, the loading screen card is removed from the stack and replaced with the main application card.
A new screen is pushed
When a user performs an action that routes them to a new screen, a card is placed on top of the main application card, thereby creating a stack of two cards. Since the main screen card has not been removed from the stack, its associated state is maintained, along with the state of the new card on the stack.
The back button pops it
When the user presses the back button, the new card is removed from the stack, returning us to the original card in the stack — the main screen — where it has maintained its own state while it was under the new screen.
Navigator, which we will discuss in the next section. What is important to note is that an application can have multipleNavigators, thereby creating nested navigation stacks.Let us dive into Navigator 1.0 and learn how all this works.
Introduction to Navigator 1.0
Flutter has both imperative and declarative routing mechanisms, using Navigator and Router, respectively.
Navigator is sometimes referred to as Navigator 1.0 whereas the Router API is sometimes referred to as Navigator 2.0. This does not mean that Router replaces Navigator — far from it (this may contrast with how one might typically consider version numbers to work, with newer versions replacing older ones). In fact, Router, as we will discuss later, is built using Navigator.We need to understand how Navigator works before we can understand Router, so let us dig into the concept, starting with the difference between imperative and declarative code, as understanding this concept is vital to understanding how Navigator and Router work.
Imperative vs. declarative
Imperative — Navigator
Navigator (the imperative system) is given a list of routes, then told to navigate to one of those routes.Declarative — Router
Router requires a bit more boilerplate code to describe how to parse the intent of a route (by, for example, pulling out arguments passed along with the route) before performing the routing action. By using Router, we are simply describing where we want to navigate to and with what properties; then Router figures out how to make that happen for us.These are not mutually exclusive, however. In fact, Router (the declarative system) is built using Navigator (the imperative system).
Pushing and popping a route
Let us explore using Navigator to route to a new screen and back. The first thing we will need is two screens to route between. One of those screens can be the main screen of your application. The other screen should have its own Scaffold and body. Feel free to use this as a starting point:
class MainScreen extends StatelessWidget {
const MainScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('This is the main screen of my application'),
),
body: Center(
child: ElevatedButton(
child: const Text('Navigate!'),
onPressed: () {
// Navigate to new screen when tapped.
},
),
),
);
}
}
class SecondScreen extends StatelessWidget {
const SecondScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("I'm so glad you found your way over. "),
),
body: Center(
child: ElevatedButton(
onPressed: () {
// Navigate back to main screen when tapped.
},
child: const Text('See you later!'),
),
),
);
}
}
Now all that is left is to set up Navigator to route from the first screen to the second, then back. On the first screen, set the onPressed method to ask Navigator to push a new card onto the stack:
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const SecondScreen()),
);
}
Tapping the button now will route you to the second screen. Getting back to the first screen is just as easy. On the second screen, set the onPressed method to ask Navigator to pop the current card off the stack:
onPressed: () {
Navigator.pop(context);
}
Runnable copy: examples/flutter_for_jobseekers_ch08/lib/navigator_1/push_pop.dart
And… that is it! You now know all there is to know about navigating to a new screen and back! Except…
- What if you want to navigate to the same screen from multiple places in your application? Would that not mean writing a bunch of duplicate code?
- What if you want to replace the current screen with the new one so a user cannot press the
backbutton to get back to a screen they should not, like when the splash screen is finished, and the user is presented with the main screen? - What if you want to pass information from the first screen to the second? This method will not work at all since no data can be passed into the route.
We have a bit more to investigate, so let us investigate each of these use cases one at a time.
Routing using named routes
Let us suppose that your application has a settings screen, which you want to be easily accessible from any screen. On each new screen you create, you add a button to navigate to the settings screen, but the onPressed method always has a Navigator.push to a MaterialPageRoute with a builder method. That is a lot of code just to navigate to a new screen! Plus, it means that we must remember exactly what our settings screen's widget name is (and what happens if you have a similarly named widget somewhere else in the application? Oh boy!) Would it not be great if we could simply route to the new screen by name? Like, hey, Navigator! Send me to the settings screen! Fortunately, we can: by using named routes.
Navigator will treat these named routes like a URL path. The difference will be that there will not be any www or .com associated with the routes since that is all handled internally. Instead, we are worried about what would come after that.It is like going to https://www.my-favorite-website.com/my-favorite-page except that Navigator knows about the https://www.my-favorite-website.com part, so we do not have to specify it. That leaves us with just the /my-favorite-page to manage. If you went to the main website, there would not be anything after the slash, so the slash itself is the root of the route. This will make more sense as we dig into some examples.Setting up the routing table
To set up named routes, you will have to find your main MaterialApp and define a couple of properties. The first thing we will need to define is the routes parameter, which contains a map of route names to the screen we are navigating to:
MaterialApp(
routes: {
'/': (context) => const MainScreen(),
'/settings': (context) => const SettingsScreen(),
},
)
The next thing we need to do is set an initial route, which will display the main content of the application when it is loaded. Before, we used to do this by specifying the home property. Now, we will use the initialRoute property — so go ahead and remove home!
MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => const MainScreen(),
'/settings': (context) => const SettingsScreen(),
},
)
Navigating to and replacing a named route
At this point, we have everything we need to solve our first two problems: we can now navigate to a named route, and we can replace a route with a new one. Let us do that.
First, to navigate to a named route, we replace Navigator.push with Navigator.pushNamed, and instead of passing in a MaterialPageRoute, we pass in the name of the route:
onPressed: () {
Navigator.pushNamed('/settings');
}
If you want to replace the current card in the stack with your new route, you use Navigator.pushReplacementNamed, instead:
onPressed: () {
Navigator.pushReplacementNamed('/settings');
}
BuildContext, so they do not compile. Like Navigator.push and Navigator.pop, the static methods take context as their first argument: Navigator.pushNamed(context, '/settings') and Navigator.pushReplacementNamed(context, '/settings'), as the runnable copy does.Of course, there is also a Navigator.pushReplacement for when you are not using named routes and navigating back whether using named routes or a MaterialPageRoute works just the same.
Storing the route name on the screen
You also have the option of specifying the route name in the destination widget. Outside of the build() method, try adding something like the following:
static const routeName = '/settings';
Then you can use it in your routing table:
routes: {
'/': (context) => const Home(),
SettingsScreen.routeName: (context) => const SettingsScreen(),
},
Companion code: Example 8.8 routes '/' to MainScreen, as the earlier examples on this page do.
Runnable copy: examples/flutter_for_jobseekers_ch08/lib/navigator_1/named_routes.dart (the book does not print SettingsScreen; the example adds a minimal one)
MaterialPageRoute.Passing arguments into a route
Sometimes it is necessary to pass some data back and forth when routing. For example, you may find yourself with a product page where the user can choose the quantity of an item to purchase, then immediately checkout their order. The checkout screen would need to know what the desired product is, the quantity, and the price. Passing in this data using arguments means you can build a more generic checkout screen, capable of accepting any item(s), in any quantity, at any price.
There are a couple of separate ways we can do this:
Arguments read by the widget
ModalRoute.of(context).onGenerateRoute
onGenerateRoute and handing them to the screen.Let us first look at the former method.
Defining an arguments class
To begin, we need to define a class that contains the arguments that we will pass into our route. Let us build one for the shopping cart example, making sure that it is flexible enough to accept multiple items when we go to checkout:
class StoreItem {
final String name;
final double price;
const StoreItem({required this.name, required this.price});
}
class CheckoutScreenArguments {
final List<Map<StoreItem, int>> shoppingCart;
const CheckoutScreenArguments(this.shoppingCart);
}
Here, we have created a StoreItem class, which will hold both the name of the item and its price. Next, we made a CheckoutScreenArguments class with one property (although we could have as many properties as we want.) This property will accept a List of Maps that map a StoreItem to the quantity of items in the cart. That might look like the following:
const StoreItem shirt = StoreItem(name: "Super Rad Shirt", price: 12.99);
const StoreItem shoes = StoreItem(name: "Comfy Shoes", price: 34.99);
const CheckoutScreenArguments shoppingCart = CheckoutScreenArguments(
[
{shirt: 4},
{shoes: 1},
],
);
Runnable copy: examples/flutter_for_jobseekers_ch08/lib/navigator_1/store.dart. The book's text lost the integer part of the prices in conversion; they are restored from the publisher's companion repository, Example 8.10 (BPB Publications, n.d.).
Reading the arguments with ModalRoute.of
Now that we have a proper screen arguments class, we need to make a couple of changes to the screen that takes the arguments. First, we will move the route name into the screen, itself (Line 2, in the following example), then we can extract the arguments using the ModalRoute.of(context) inherited widget (Lines 8 and 9):
class CheckoutScreen extends StatelessWidget {
static const routeName = '/checkout';
const CheckoutScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final args =
ModalRoute.of(context)!.settings.arguments as CheckoutScreenArguments;
return Scaffold(
body: ListView.builder(
itemCount: args.shoppingCart.length,
itemBuilder: ((context, index) => ListTile(
title: Text(args.shoppingCart[index].keys.first.name),
subtitle: Text(
'${args.shoppingCart[index].values.first} × ${args.shoppingCart[index].keys.first.price}'),
)),
),
);
}
}
Now that you have a variable holding the screen arguments, all that is left is to pass your shopping cart over to the checkout screen:
ElevatedButton(
child: const Text('Checkout'),
onPressed: () {
Navigator.pushNamed(
context,
CheckoutScreen.routeName,
arguments: shoppingCart,
);
},
),
Runnable copy: examples/flutter_for_jobseekers_ch08/lib/navigator_1/route_arguments.dart (adds a ProductScreen that holds the Checkout button)
Using onGenerateRoute
That is all it takes to pass arguments into a route! There is another way we can do it, though. The second method uses the onGenerateRoute parameter in your MaterialApp. Using this method, you do not need to extract the arguments inside the widget using ModalRoute.of(context):
MaterialApp(
onGenerateRoute: (settings) {
if (settings.name == MessageScreen.routeName) {
final args = settings.arguments as MessageScreenArguments;
return MaterialPageRoute(
builder: (context) {
return MessageScreen(
title: args.title,
message: args.message,
);
},
);
}
if (settings.name == CheckoutScreen.routeName) {
final args = settings.arguments as CheckoutScreenArguments;
return MaterialPageRoute(
builder: (context) {
return CheckoutScreen(
shoppingCart: args.shoppingCart,
);
},
);
}
assert(false, 'Need to implement ${settings.name}');
return null;
},
)
In this example, we are building a MessageScreen using a MessageScreenArguments class, as well as our trusty CheckoutScreen using a CheckoutScreenArguments class.
CheckoutScreen above has no shoppingCart parameter; its only constructor parameter is key, because it reads the cart from ModalRoute.of(context). For onGenerateRoute, the screen takes the cart through its constructor (final List<Map<StoreItem, int>> shoppingCart; and required this.shoppingCart) and reads that field instead of args. The book does not print MessageScreen and MessageScreenArguments; the runnable copy defines both.MaterialApp. For this reason, it is common to break out the method into its own file, which would look something like in the following example:MaterialApp(
onGenerateRoute: routeHandler,
);
// The following method can be saved to a different file, then imported.
MaterialPageRoute? routeHandler(settings) {
(settings) {
if (settings.name == MessageScreen.routeName) {
final args = settings.arguments as MessageScreenArguments;
return MaterialPageRoute(
builder: (context) {
return MessageScreen(
title: args.title,
message: args.message,
);
},
);
}
assert(false, 'Route handler not configured for ${settings.name}');
return null;
};
}
routeHandler never routes anywhere. Its body is a single closure expression, (settings) { ... };, which is created and thrown away without being called, so the function falls off its end and always returns null, and onGenerateRoute fails for every route name. The if statements belong directly in the function body, with a typed parameter: MaterialPageRoute? routeHandler(RouteSettings settings) { if (...) ... }, as the runnable copy does.Runnable copy: examples/flutter_for_jobseekers_ch08/lib/navigator_1/on_generate_route.dart (with MessageScreen, MessageScreenArguments and a HomeScreen to start from)
Ultimately, Flutter gives you the flexibility to build your application in a way that makes the most sense for whatever project you are working on. Using onGenerateRoute in this way may be overkill, especially if only one or two of your screens require arguments. That will be up to you to decide.
onGenerateRoute for? (Here is a hint for one thing you could use it for: analytics.)Returning data from a screen
Passing data to a new screen is extremely useful, but sometimes we want to pass data back to the screen we were just looking at. You are building an input that asks your user to choose between two options. The design of the option picker is such that it would be clearer to the user by being on its own screen, rather than inline on the form. The user taps on a widget which routes them to a new screen where they make their selection, and then they are routed back to the initial screen where their option is used to update the form. The question becomes: how do we accomplish passing the data back to the initial screen after they have made their selection?
await the result and pass the data back in the Navigator.pop method.The two screens
Let us start by building a simple screen where we will both display the result of the selection and a button that we will use to route to the selection screen. We know this will need to be a StatefulWidget because we need to update the widgets based on the return value:
class _HomeState extends State<Home> {
String? _chosenOption;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Text(_chosenOption ?? ''),
ElevatedButton(
child: const Text('Choose one'),
onPressed: () {
// TODO: Route to the option screen and get the value back
},
),
],
),
);
}
}
Since _chosenOption is nullable, the Text will display nothing, for now. Next, we need a screen to route to, which includes our options:
class ChooseOneScreen extends StatelessWidget {
const ChooseOneScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
ElevatedButton(
child: const Text('Option One'),
onPressed: () {
// TODO: Return “Option One”
},
),
ElevatedButton(
child: const Text('Option Two'),
onPressed: () {
// TODO: Return “Option Two”
},
),
],
),
);
}
}
Popping with a value
Now that we have all the boilerplate code in place, we need to write the onPressed methods. Let us look at the buttons on the ChooseOneScreen first. For those, we will need to pop the current route off the stack, then return the value to the initial screen. Previously we used Navigator.pop(context) to route back to the previous screen without returning a value. We will do the same thing here, the only difference will be that we are adding another argument to the method, being the value that we would like to return.
Update each of the onPressed methods to pop the route with an appropriate return value. In this case, we know that we expect a String to be returned, so let us return exactly that. Here is an example for the first button:
onPressed: () {
Navigator.pop(context, 'Option One');
},
Awaiting the result
Next, we need to route to the screen from the initial one and wait for the value to be returned. Back on the initial screen, let us start by creating an onPressed method that navigates to our new screen:
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const ChooseOneScreen(),
),
);
},
This will let us route to the screen, but it lacks a way to receive data when we pop the route. As mentioned before, we want to await the result and the first step of that is turning our onPressed method into an async method. Then, we can await the Navigator call:
onPressed: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const ChooseOneScreen(),
),
);
},
Finally, by assigning the result of the Navigator call to a variable, we can successfully retrieve the data which was returned from the popped route:
onPressed: () async {
String? _chosenOption = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const ChooseOneScreen(),
),
);
print('The chosen option is $_chosenOption');
},
Companion code: Example 8.20 logs the result with log from dart:developer instead of print, and calls setState(() {}) after it.
If this is combined with a stateful widget and setState, you could capture the value and display it on the screen. Alternatively, you could capture the returned value and pass it into a method to parse and perform an action upon. Truly, the options are limitless.
Runnable copy: examples/flutter_for_jobseekers_ch08/lib/navigator_1/return_data.dart (stores the result with setState, so the Text shows the chosen option)
Animating a widget from one route to another
There is an enormous difference between creating a fully functioning application and an application that is well-polished.
Fully functioning
Well-polished
Animations are an integral design element that serves to smooth out state transitions and focus a user's attention on the right place at the right time. They can be subtle or grand but serve the same purpose. When you push or pop a route, Flutter creates a subtle animation to indicate that you have changed screens. Still, the content from one screen to the next, although it may be related, appears to disappear from one and re-appear on the other.
Let us build a couple of screens to play with:
class Home extends StatelessWidget {
const Home({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
const Icon(Icons.flutter_dash),
ElevatedButton(
child: const Text('Say "hi" to Dash!'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const HelloDash(),
),
);
},
),
],
),
);
}
}
class HelloDash extends StatelessWidget {
const HelloDash({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.flutter_dash,
color: Colors.blue,
size: 128,
),
const Text('Hi Dash!'),
ElevatedButton(
child: const Text('Back'),
onPressed: () {
Navigator.pop(context);
},
),
],
),
),
);
}
}
In this example, we have an icon of Dash with a button that routes to a new screen. The new screen has a larger, more colorful version of the same icon. There is a subtle animation when the route transitions, but otherwise, Dash appears to teleport from one place to another. How do we know this is the same Dash that was on the previous screen?
Let us fix this by making Dash fly! Wrap the Icon widget on both screens with a Hero widget and give them both a tag property with the same value:
const Hero(
tag: 'dash',
child: ...,
),
Runnable copy: examples/flutter_for_jobseekers_ch08/lib/navigator_1/hero_animation.dart
Now, tapping the button makes Dash fly from one screen to the next!
Hero will help the user keep track of how elements on the two screens relate, adding polish to the finished product.The Hero widget is one of many widgets which can be used to animate elements in Flutter. Although animating widgets in Flutter is not covered in this book, there are loads of excellent resources online which cover many aspects of animating widgets, including creating your own animations. Check the Further reading section at the end of this chapter for a link to the documentation.
Introduction to Navigator 2.0 — the Router API
What Navigator 1.0 lacks in ability, it makes up for with simplicity. Unfortunately, the simplicity of Navigator 1.0 can be quite limiting at times. It is not hard to imagine a scenario wherein one would want to:
Custom transitions
Deep linking
/contact/0 telling the application to show us the first contact.Nested routing
More elaborate applications are usually better served by Navigator 2.0.
The Router API is not a breaking change. Rather, it adds a new set of APIs for us to leverage and build more complex applications with far more freedom. With that freedom, however, comes a lot more complexity. Let us first start by looking at a diagram of how the Router API works (Figure 8.1):

Figure 8.1: A flow-chart of the functionality of the Router API. Source: https://medium.com/flutter/learning-flutters-new-navigation-and-routing-system-7c9068155ade
What we will build
We are going to be implementing each of these blocks to create a complete Router API-enabled application. Using our earlier examples, we are going to create a simple application that lists several contacts and routes to a contact details screen when we tap on one.
Flutter Web
Back button handling
Custom transition
404 page
The boilerplate
To get started, we will need to set up a Contact class, build the base application screen, create a screen that lists the contacts, a contact details screen, and a 404 screen. Since we haven't set up any routing yet, we will have no way to navigate between these screens, but once we are done, it will be nice to have gotten the boilerplate code out of the way.
Without further ado, here is the boilerplate code for our application:
import 'package:flutter/material.dart';
void main() {
runApp(const ContactsApp());
}
class ContactsApp extends StatefulWidget {
const ContactsApp({super.key});
@override
State<StatefulWidget> createState() => _ContactsAppState();
}
class _ContactsAppState extends State<ContactsApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Contacts App',
home: Container(),
);
}
}
class Contact {
final String name;
final String email;
const Contact({
required this.name,
required this.email,
});
}
class ContactsListScreen extends StatelessWidget {
final List<Contact> contacts;
final ValueChanged<Contact> onTapped;
const ContactsListScreen({
super.key,
required this.contacts,
required this.onTapped,
});
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: [
for (final Contact contact in contacts)
ListTile(
title: Text(contact.name),
subtitle: Text(contact.email),
onTap: () => onTapped(contact),
)
],
),
);
}
}
class ContactDetailsScreen extends StatelessWidget {
final Contact contact;
const ContactDetailsScreen({
super.key,
required this.contact,
});
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
contact.name,
style: Theme.of(context).textTheme.headline6,
),
Text(
contact.email,
style: Theme.of(context).textTheme.subtitle1,
),
],
),
),
),
);
}
}
headline6 and subtitle1 no longer exist, so this code does not compile on current Flutter. The 2018 TextTheme names were deprecated in favor of the Material 3 names and then removed (flutter/flutter, n.d.). Use titleLarge for headline6 and titleMedium for subtitle1, as the runnable copy does.Corrected: the 404 screen announced above is missing from the boilerplate, but the RouterDelegate below uses it as UnknownScreen. The book prints it only in the Beamer version at the end of the chapter: a StatelessWidget whose build returns const Scaffold(body: Center(child: Text('Oops.'))). The runnable copy keeps the shared screens in lib/contacts.dart.The only thing that might be new in this code is the ValueChanged widget. When combined with the notifyListeners() method, we can trigger widget rebuilds when values are changed.
ValueChanged is not a widget. It is a typedef for a callback, typedef ValueChanged<T> = void Function(T value), a "Signature for callbacks that report that an underlying value has changed" (Flutter, n.d.-d). ContactsListScreen calls onTapped(contact); the rebuild comes from the RouterDelegate, whose _handleContactTapped (the function passed as onTapped) calls notifyListeners().The pieces of the Router API
Now that we have our boilerplate code in place, we can start thinking about the different pieces that make up the Router API. At a minimum, we will need a RouterDelegate and a RouteInformationParser, but what are these?
Router learns about and responds to changes in the routing state. It receives the initial route intents and maintains the routing state, then uses this information to build the Navigator with the current list of Pages in the navigation stack. It is the object that sets up the current configuration of the Router.Navigator's history stack. Page objects return a PageRouteBuilder object from their createRoute() method.Pages for the Navigator. An application will have a Navigator (managed by a Router widget), which is given a list of Pages.settings parameter and a pageBuilder parameter. The settings parameter accepts a value of a nullable RouteSettings object and the pageBuilder returns the widget we will eventually show the user.RouterDelegate wants to work with. It, along with the RouterDelegate, are both passed into the Router.Yeah, the Router API is complex.
The RoutePath
Let us just start building out these pieces and see how they work as we go. First, let us create our RouterDelegate and RouteInformationParser objects. We will also need to create a RoutePath, which is a representation of the raw URI that the RouterDelegate will work with, so let us start there:
class ContactRoutePath {
final int? id;
final bool isUnknown;
ContactRoutePath.details(this.id) : isUnknown = false;
ContactRoutePath.home()
: id = null,
isUnknown = false;
ContactRoutePath.unknown()
: id = null,
isUnknown = true;
bool get isDetailsPage => id != null;
bool get isHomePage => id == null;
}
This class takes in a nullable integer id. We will call this class using a constructor later, which could mean calling ContactRoutePath.home() or ContactRoutePath.details(id). This will make more sense once we put it to use in our RouterDelegate, so let us build that next.
The RouterDelegate
class ContactRouterDelegate extends RouterDelegate<ContactRoutePath>
with ChangeNotifier, PopNavigatorRouterDelegateMixin<ContactRoutePath> {
static const List<Contact> contacts = [
Contact(name: 'Alice', email: '[email protected]'),
Contact(name: 'Bob', email: '[email protected]'),
Contact(name: 'Charlie', email: '[email protected]'),
];
@override
final GlobalKey<NavigatorState> navigatorKey;
bool show404 = false;
Contact? _selectedContact;
ContactRouterDelegate() : navigatorKey = GlobalKey<NavigatorState>();
@override
ContactRoutePath get currentConfiguration {
if (show404) {
return ContactRoutePath.unknown();
}
return _selectedContact == null
? ContactRoutePath.home()
: ContactRoutePath.details(contacts.indexOf(_selectedContact!));
}
@override
Widget build(BuildContext context) {
return Navigator(
key: navigatorKey,
pages: [
MaterialPage(
key: const ValueKey('ContactsListPage'),
child: ContactsListScreen(
contacts: contacts,
onTapped: _handleContactTapped,
),
),
if (_selectedContact != null)
ContactDetailsPage(contact: _selectedContact!),
if (show404)
const MaterialPage(
key: ValueKey('UnknownPage'),
child: UnknownScreen(),
),
],
onPopPage: (route, result) {
if (!route.didPop(result)) {
return false;
}
_selectedContact = null;
show404 = false;
notifyListeners();
return true;
},
);
}
@override
Future<void> setNewRoutePath(ContactRoutePath configuration) async {
if (configuration.isUnknown) {
_selectedContact = null;
show404 = true;
return;
}
if (!configuration.isDetailsPage) {
_selectedContact = null;
}
if (configuration.id == null) {
_selectedContact = null;
show404 = false;
return;
}
if (configuration.id! < 0 || configuration.id! > contacts.length - 1) {
show404 = true;
return;
}
_selectedContact = contacts[configuration.id!];
show404 = false;
}
void _handleContactTapped(Contact contact) {
_selectedContact = contact;
notifyListeners();
}
}
This is where our RoutePath comes into play. (This is also where we specify our list of contacts — although, in a production application, these would be stored somewhere else. For the sake of simplicity, we are just going to specify a static list of contacts, though.)
onPopPage is deprecated: "This is deprecated and replaced by onDidRemovePage" (Flutter, n.d.-b), deprecated after Flutter 3.16, and flutter analyze reports it. onDidRemovePage(page) runs after a page has left the stack, whether it was popped (back button) or dropped from pages (a new URL), so it must reset only the state of the page that is still current, or a new deep link from /contact/0 to /contact/1 would clear the newly selected contact. The runnable copy uses:onDidRemovePage: (page) {
if (page is ContactDetailsPage && page.contact == _selectedContact) {
_selectedContact = null;
} else if (page.key == const ValueKey('UnknownPage') && show404) {
show404 = false;
} else {
return;
}
notifyListeners();
},
The RouterDelegate is what returns the Navigator widget, which we discussed earlier. There are two flows that the RouterDelegate controls:
Platform to user
RouteInformation) comes (through RouteInformationProvider) to our app and RouteInformationParser parses it into our ContactRoutePath, then the setNewRoutePath() is called where RouterDelegate configures the routing state (show404, _selectedContact, and so on) to match the incoming route information and build the Navigator.User to platform
_handleContactTapped), the routing state is first updated and notifyListeners is called. This will trigger both a rebuild of Navigator and cause the platform to fetch the currentConfiguration (for example, causing the browser to update the URI). Here, the RouteInformationParser is again used to restore (parse back) the current ContactRoutePath into a RouteInformation that the platform can understand.The RouteInformationParser
Now, let us implement the RouteInformationParser, which is the object that converts the raw URI back and forth into something that the RouterDelegate understands:
class ContactRouteInformationParser
extends RouteInformationParser<ContactRoutePath> {
@override
Future<ContactRoutePath> parseRouteInformation(
RouteInformation routeInformation,
) async {
final Uri uri = Uri.parse(routeInformation.location!);
// Handle '/'
if (uri.pathSegments.isEmpty) {
return ContactRoutePath.home();
}
// Handle '/contact/:id'
if (uri.pathSegments.length == 2) {
if (uri.pathSegments[0] != 'contact') return ContactRoutePath.unknown();
String remaining = uri.pathSegments[1];
int? id = int.tryParse(remaining);
if (id == null) return ContactRoutePath.unknown();
return ContactRoutePath.details(id);
}
// Handle unknown routes
return ContactRoutePath.unknown();
}
@override
RouteInformation? restoreRouteInformation(ContactRoutePath configuration) {
if (configuration.isUnknown) {
return const RouteInformation(location: '/404');
}
if (configuration.isHomePage) {
return const RouteInformation(location: '/');
}
if (configuration.isDetailsPage) {
return RouteInformation(location: '/contact/${configuration.id}');
}
return null;
}
}
The parseRouteInformation method is what does the heavy lifting of pulling the parameters out of the URI, whereas the restoreRouteInformation method is what returns the RouteInformation that is used to set the new URI.
RouteInformation.location is deprecated: "Use uri instead. This feature was deprecated after v3.8.0-3.0.pre." (Flutter, n.d.-c). location is also no longer nullable, so the ! only produces a warning. Read the parsed Uri directly with final Uri uri = routeInformation.uri;, and create the objects with RouteInformation(uri: Uri.parse('/404')) (these can no longer be const), as the runnable copy does.Wiring it into the app
That is a ton of boilerplate code, but all of it is necessary! Let us update our application to use it:
class _ContactsAppState extends State<ContactsApp> {
final ContactRouterDelegate _routerDelegate = ContactRouterDelegate();
final ContactRouteInformationParser _routeInformationParser =
ContactRouteInformationParser();
@override
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'Contacts App',
routerDelegate: _routerDelegate,
routeInformationParser: _routeInformationParser,
);
}
}
At this point, everything should work as expected — the list of contacts, tapping to view the contact details, the URI updating, the back button — everything.
A custom page transition
There is one more tweak we can make to this. Let us change the page transition:
class ContactDetailsPage extends Page {
final Contact contact;
ContactDetailsPage({
required this.contact,
}) : super(key: ValueKey(contact));
@override
Route createRoute(BuildContext context) {
return PageRouteBuilder(
settings: this,
pageBuilder: (context, animation, animation2) {
final tween = Tween(
begin: const Offset(1.0, 0),
end: Offset.zero,
);
final curveTween = CurveTween(
curve: Curves.easeInOut,
);
return SlideTransition(
position: animation.drive(curveTween).drive(tween),
child: ContactDetailsScreen(
key: ValueKey(contact),
contact: contact,
),
);
},
);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch08/lib/main.dart (the whole Router API app; its tests open deep links, the 404 page and press the system back button)
Here, the pageBuilder ends up building a SlideTransition animation instead of the default animation.
SlideTransition?The Router API is, as we have seen, significantly more complex than Navigator 1.0. Although we moved quickly through it and did not examine every line of code (which could have been its own book!), we do have a working example from which we can build upon later and study further.
Using packages to help with routing
Expectedly, a lot of packages emerged that try to simplify the usage of the Router API. Let us see an implementation of the same app using one of them — Beamer, which was created by Sandro Lovnički (@slovnicki).
Here is the same application we just wrote using the Router API, this time written using Beamer as a basis:
import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const ContactsApp());
}
class Contact {
final String name;
final String email;
const Contact({
required this.name,
required this.email,
});
}
class ContactDetailsScreen extends StatelessWidget {
final Contact contact;
const ContactDetailsScreen({super.key, required this.contact});
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
contact.name,
style: Theme.of(context).textTheme.headline6,
),
Text(
contact.email,
style: Theme.of(context).textTheme.subtitle1,
),
],
),
),
),
);
}
}
class ContactsApp extends StatefulWidget {
const ContactsApp({super.key});
@override
State<StatefulWidget> createState() => _ContactsAppState();
}
class ContactsListScreen extends StatelessWidget {
final List<Contact> contacts;
final ValueChanged<Contact> onTapped;
const ContactsListScreen({
super.key,
required this.contacts,
required this.onTapped,
});
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: [
for (final Contact contact in contacts)
ListTile(
title: Text(contact.name),
subtitle: Text(contact.email),
onTap: () => onTapped(contact),
)
],
),
);
}
}
class UnknownScreen extends StatelessWidget {
const UnknownScreen({super.key});
@override
Widget build(BuildContext context) {
return const Scaffold(
body: Center(
child: Text('Oops.'),
),
);
}
}
class _ContactsAppState extends State<ContactsApp> {
static const List<Contact> contacts = [
Contact(name: 'Alice', email: '[email protected]'),
Contact(name: 'Bob', email: '[email protected]'),
Contact(name: 'Charlie', email: '[email protected]'),
];
final _routerDelegate = BeamerDelegate(
setBrowserTabTitle: false,
notFoundRedirectNamed: '/404',
locationBuilder: RoutesLocationBuilder(
routes: {
'/': (context, _, __) => ContactsListScreen(
contacts: contacts,
onTapped: (contact) => context.beamToNamed(
'/contact/${contacts.indexOf(contact)}',
),
),
'/contact/:id': (_, state, __) {
final id = int.parse(state.pathParameters['id']!);
return BeamPage(
key: ValueKey('contact-$id'),
type: BeamPageType.slideRightTransition,
popToNamed: '/',
child: ContactDetailsScreen(contact: contacts[id]),
);
},
'/404': (_, __, ___) => const UnknownScreen(),
},
),
guards: [
BeamGuard(
pathPatterns: ['/contact/*'],
check: (_, beamLocation) {
final beamState = beamLocation.state as BeamState;
final idParameter = beamState.pathParameters['id'];
if (idParameter != null) {
final id = int.tryParse(idParameter);
if (id == null || id < 0 || id >= contacts.length) {
return false;
}
}
return true;
},
beamToNamed: (_, __) => '/404',
)
],
);
final _routeInformationParser = BeamerParser();
@override
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'Contacts App',
routerDelegate: _routerDelegate,
routeInformationParser: _routeInformationParser,
);
}
}
headline6 and subtitle1 have been removed; use titleLarge and titleMedium. With Beamer 1.7.0 the rest compiles as printed; the runnable copy only adds .call after RoutesLocationBuilder(...), because the analyzer flags passing a callable object where a function is expected (lint implicit_call_tearoffs).Runnable copy: examples/flutter_for_jobseekers_ch08/lib/beamer/main.dart (uses the shared screens in lib/contacts.dart)
flutter.dev (pub.dev, n.d.). Beamer still works with current Flutter, but its latest release, 1.7.0, dates from October 2024.Conclusion
Navigation and routing are ubiquitous in just about any application you will end up building. Having a firm understanding of how these systems work in Flutter is key to building any application which has more than a single screen (which will be most, if not all, of them!)
In the upcoming chapter, we will be looking at state management and the BLoC pattern (a commonly used state management system.) These systems will open a lot of new possibilities for us to build dynamic and complex experiences. So, refill your water, do some stretches, and when you are ready, let us dive into state management!
Questions
- The concept of sending a user from one screen to another is known as what?
- What is the difference between navigation and routing?
- When navigating between screens in Flutter, what analogy is useful in visualizing how different screens and their states are maintained?
- What is the difference between imperative and declarative routing?
- What widget is used to route imperatively in Flutter? What widget is used to route declaratively?
- What are some of the limitations of Navigator 1.0?
- How do you configure named routes, then navigate to a route by name?
- What's the difference between
Navigator.pushandNavigator.pushReplacement? - What happens if you use
Navigator.pushReplacementfollowed byNavigator.popon the new screen? - How do you pass data to a new route? How do you get a value back when calling
Navigator.pop? - What useful things can you use
onGenerateRoutefor? - What widget can be used to animate a widget from one screen to another?
- What is the correct name for Navigator 2.0?
- How are the
ValueChangedwidget andnotifyListeners()method used? - What is a
RouterDelegate? - How do you change the transition animation when navigating to a new route using the Router API?
Key terms
Further reading
References
- BPB Publications. (n.d.). Flutter for Jobseekers (companion code repository). Retrieved from GitHub: https://github.com/bpbpublications/Flutter-for-Jobseekers (added, not in the book)
- Flutter. (n.d.-a). Navigation and routing. Retrieved from Flutter: https://docs.flutter.dev/ui/navigation (added, not in the book)
- Flutter. (n.d.-b). onPopPage property. Retrieved from Flutter API: https://api.flutter.dev/flutter/widgets/Navigator/onPopPage.html (added, not in the book)
- Flutter. (n.d.-c). location property. Retrieved from Flutter API: https://api.flutter.dev/flutter/widgets/RouteInformation/location.html (added, not in the book)
- Flutter. (n.d.-d). ValueChanged typedef. Retrieved from Flutter API: https://api.flutter.dev/flutter/foundation/ValueChanged.html (added, not in the book)
- Flutter. (n.d.-e). Introduction to animations. Retrieved from Flutter: https://docs.flutter.dev/ui/animations (added, not in the book)
- flutter/flutter. (n.d.). Remove deprecated
TextThememembers (#139255). Retrieved from GitHub: https://github.com/flutter/flutter/pull/139255 (added, not in the book) - pub.dev. (n.d.). go_router. Retrieved from pub.dev: https://pub.dev/packages/go_router (added, not in the book)
Working with APIs and Asynchronous Operations
Futures and async/await, requesting and sending data with the http package, turning JSON into Dart classes, FutureBuilder and StreamBuilder, and sinks and streams.
State Management and the BLoC
Ephemeral versus app state, and one shopping cart built four ways — with an inherited widget, Provider, Cubit and BLoC.