Flutter for Jobseekers

Navigation and Routing

Navigator 1.0 (push and pop, named routes, route arguments, returning data, Hero animations), the Router API (Navigator 2.0), and routing with Beamer.

Navigation and Routing

Most modern applications have their content organized in multiple, distinct screens, which break up a workflow from being a single and monolithic behemoth into smaller and purpose-driven views. The concept of sending a user from one screen to another is routing, which we accomplish using the action of navigation. A user navigates to a new screen, where the application then routes them to it.

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.

Companion code: the publisher's repository holds this chapter's code as 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

After finishing this chapter, you will be able to accurately describe the concepts behind navigation and routing. You will be able to use this knowledge to build a simple application that uses Flutter's most basic navigation system, then learn how to use the newer and more powerful system which was introduced later. Finally, you will learn how to simplify a more complex routing scenario by using a package from Pub.

Runnable example

The chapter's Navigator 1.0 demos, the Router API contacts app and the Beamer contacts app are also available as a runnable project with tests in 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

Flutter can retain state for screens not currently being displayed to the user, but from which they had previously navigated.
The best way to visualize this is to consider a deck of playing cards. When navigating around the Web, only a single playing card can be on the table at a time. When navigating within Flutter, however, cards are added and removed from the stack of cards on the table.

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.

This whole navigating and routing process of stacking cards happens inside the scope of a 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.

Before we break down what that means, it is important to note that 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

Code that is imperative has step-by-step instructions to complete the task at hand. Navigator (the imperative system) is given a list of routes, then told to navigate to one of those routes.

Declarative — Router

Declarative code simply provides a description of what you want but not necessarily how to go about getting it. 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:

Example 8.1 · Example 8.1.dart
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:

Example 8.2 · Example 8.2.dart
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:

Example 8.3 · Example 8.3.dart
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 back button 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.

Named routes will look familiar to anyone who has used a Web browser before. Each route will look like a path in a URL. In fact, 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:

Example 8.4 · Example 8.4.dart
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!

Example 8.5 · Example 8.5.dart
MaterialApp(
  initialRoute: '/',
  routes: {
    '/': (context) => const MainScreen(),
    '/settings': (context) => const SettingsScreen(),
  },
)

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:

Example 8.6 · Example 8.6.dart
onPressed: () {
  Navigator.pushNamed('/settings');
}

If you want to replace the current card in the stack with your new route, you use Navigator.pushReplacementNamed, instead:

Example 8.7 · Example 8.7.dart
onPressed: () {
  Navigator.pushReplacementNamed('/settings');
}
Corrected: both calls are missing the 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:

Example 8.8 · Example 8.8.dart
static const routeName = '/settings';

Then you can use it in your routing table:

Example 8.8 · Example 8.8.dart
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)

Using named routes is an excellent and effortless way to keep the routing in your app clean and simple. If you decide to write a new settings screen but you do not want to immediately remove the old one, it is much easier to update the named route than it is to track down all the different places where you are generating a MaterialPageRoute.
Corrected: the Flutter team no longer recommends named routes for most apps. "Although named routes can handle deep links, the behavior is always the same and can't be customized. When a new deep link is received by the platform, Flutter pushes a new Route onto the Navigator regardless of where the user currently is. Flutter also doesn't support the browser forward button for applications using named routes. For these reasons, we don't recommend using named routes in most applications. Instead, use a routing package like go_router or use Navigator with MaterialPageRoute" (Flutter, n.d.-a).

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

Defining the arguments and passing them into the widget, which extracts them with ModalRoute.of(context).

onGenerateRoute

Extracting the arguments using 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:

Example 8.9 · Example 8.9.dart
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:

Example 8.10 · Example 8.10.dart
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):

Example 8.11 · Example 8.11.dart
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:

Example 8.12 · Example 8.12.dart
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):

Example 8.13 · Example 8.13.dart
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.

Corrected: the 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.
While this reduces the complexity of the individual screens you are routing to, it increases the complexity of your 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:
Example 8.14 · Example 8.14.dart
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;
  };
}
Corrected: this 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.

Can you think of another thing that you can use 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?

The solution is much simpler than one might imagine. When routing to a new screen, you can simply 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:

Example 8.15 · Example 8.15.dart
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:

Example 8.16 · Example 8.16.dart
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:

Example 8.17 · Example 8.17.dart
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:

Example 8.18 · Example 8.18.dart
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:

Example 8.19 · Example 8.19.dart
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:

Example 8.20 · Example 8.20.dart
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

Assumes you have met the bare minimum in terms of the app meeting the functional goals.

Well-polished

Implies that you have taken the time to think about the look and feel of the application. A well-polished application does not just include a well-coordinated color scheme and widgets that look and feel like they belong together and support each other. A well-polished application uses animations to unify the experience for the user.

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:

Example 8.21 · Example 8.21.dart
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:

Example 8.22 · Example 8.22.dart
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!

Choosing one or two elements to transition between routes as a 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

Implement a custom screen transition animation.

Deep linking

Route within the application based on a URI, such as /contact/0 telling the application to show us the first contact.

Nested routing

Use nested routing.

More elaborate applications are usually better served by Navigator 2.0.

When Navigator 2.0 was first introduced, it was named as such. This is still the name by which many people know it and refer to it as. However, the more appropriate name that has since been adopted by the Flutter team is the Router API.

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

We will target Flutter Web, just so we can observe the URI changing (although in true Flutter form, the application works anywhere.)

Back button handling

We will implement back button handling, so we can use a system back button (for example, Android's back button).

Custom transition

We will customize the screen transition.

404 page

We will even add a custom 404 page just in case the user tries to enter an invalid path.

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:

Example 8.23 · Example 8.23.dart
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,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
Corrected: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.

Corrected: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?

RouterDelegate
Defines the behavior of how the application's 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.
Page
Used to set the Navigator's history stack. Page objects return a PageRouteBuilder object from their createRoute() method.
Router
Configures the list of Pages for the Navigator. An application will have a Navigator (managed by a Router widget), which is given a list of Pages.
PageRouteBuilder
Has both a 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.
RouteInformationParser
Used to parse the raw URI into an object that 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:

Example 8.24 · Example 8.24.dart
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

Example 8.25 · Example 8.25.dart
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.)

Corrected: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

When a URI (as 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

When we navigate within the app (for example, with _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:

Example 8.26 · Example 8.26.dart
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.

Corrected: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:

Example 8.27 · Example 8.27.dart
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:

Example 8.28 · Example 8.28.dart
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.

What other animations or transitions could you use instead of a 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).

As we will see, a lot of things we needed to implement by hand before are abstracted out for us in Beamer. In fact, all we need to define are the routes we want to handle and, optionally, how we want to handle them. Beamer also has an advanced API that we could use, but that is a topic for another day.

Here is the same application we just wrote using the Router API, this time written using Beamer as a basis:

Example 8.29 · Example 8.29.dart
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,
    );
  }
}
Corrected: as in the Router API version, 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)

As you can see, the same application using Beamer simultaneously harnesses the power of the Router API while delivering something nearing the simplicity of Navigator 1.0.
(added, not in the book) The Flutter documentation now names go_router as its example of a routing package: "Flutter applications with advanced navigation and routing requirements (such as a web app that uses direct links to each screen, or an app with multiple Navigator widgets) should use a routing package such as go_router that can parse the route path and configure the Navigator whenever the app receives a new deep link" (Flutter, n.d.-a). go_router is published on pub.dev by the verified publisher 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

  1. The concept of sending a user from one screen to another is known as what?
  2. What is the difference between navigation and routing?
  3. When navigating between screens in Flutter, what analogy is useful in visualizing how different screens and their states are maintained?
  4. What is the difference between imperative and declarative routing?
  5. What widget is used to route imperatively in Flutter? What widget is used to route declaratively?
  6. What are some of the limitations of Navigator 1.0?
  7. How do you configure named routes, then navigate to a route by name?
  8. What's the difference between Navigator.push and Navigator.pushReplacement?
  9. What happens if you use Navigator.pushReplacement followed by Navigator.pop on the new screen?
  10. How do you pass data to a new route? How do you get a value back when calling Navigator.pop?
  11. What useful things can you use onGenerateRoute for?
  12. What widget can be used to animate a widget from one screen to another?
  13. What is the correct name for Navigator 2.0?
  14. How are the ValueChanged widget and notifyListeners() method used?
  15. What is a RouterDelegate?
  16. How do you change the transition animation when navigating to a new route using the Router API?

Key terms

Declarative programming
Code that provides a description of the expected outcome but not instructions to accomplish it.
Imperative programming
Code that has step-by-step instructions to complete the task at hand.
Intent
The expected outcome of a user's action.

Further reading

Animations in Flutter

Flutter's documentation on animating widgets.

All about Beamer

The Beamer website; the package is at https://pub.dev/packages/beamer.

Learning Navigator 2.0 (the Router API)

An article on the Router API in the Flutter publication on Medium, the source of Figure 8.1.

go_router (added, not in the book)

The routing package named in Flutter's navigation documentation.
Corrected: the book's animations link, https://docs.flutter.dev/development/ui/animations, now redirects to https://docs.flutter.dev/ui/animations (Flutter, n.d.-e).

References

Copyright © 2026