Today we’re going to look at navigation in Flutter.
But not just any boring navigation. ?
No, ladies and gentlemen, we’re going to make this interesting.
Here’s an app with a BottomNavigationBar:
What we want is for each tab to have its own navigation stack. This is so that we don’t lose the navigation history when switching tabs. Example:
How to build this? Short version:
- Create an app with a
- In the
Scaffoldbody, create a
Stackwith one child for each tab.
- Each child is an
Offstagewidget with a child
- Don’t forget to handle Android back navigation with
Want the longer and more interesting explanation? First, a couple of disclaimers:
- This article assumes you are familiar with navigation in Flutter. See the Navigation basics tutorial, as well as the Navigator, MaterialPageRoute, and MaterialApp classes for more context.
- Some of this code is experimental. If you know of a better way, please let me know.
Ok, let’s get started.
It’s all about the navigators
All Flutter apps always define a
MaterialApp. Normally this sits at the root of the widget tree:
Then, we can define our
App class like so:
BottomNavigation is a custom widget that draws the three tabs with the correct colors, using
BottomNavigationBar. It takes the
currentTab as an input and calls the
_selectTab method to update the state as needed.
The interesting part is the
_buildBody() method. For simplicity, we can start by adding a
FlatButton with a callback to push a new page:
How does the
_push() method work?
MaterialPageRoutetakes care of creating a new route to be pushed
Navigatorup the widget tree, and uses it to push the new route.
You may wonder, where does the
Navigator come from?
We haven’t created one ourselves and the parent of our
App class is the
MaterialApp at the root of the widget tree.
As it turns out,
MaterialApp creates its own
However, if we just use
Navigator.of(context) to push the new route, something unexpected happens.
BottomNavigationBar and its contents slide away as the new page is presented. Not cool. ?
What we actually want is for the detail page to be pushed over the main page, but to keep the
BottomNavigationBar at the bottom.
This does not work because
Navigator.of(context) finds an ancestor of the
BottomNavigatorBar itself. In fact, the widget tree looks something like this:
▼ MyApp ▼ MaterialApp ▼ <some other widgets> ▼ Navigator ▼ <some other widgets> ▼ App ▼ Scaffold ▼ body: <some other widgets> ▼ BottomNavigationBar
And if we open up the Flutter inspector, here it is:
If we could use a
Navigator that is not an ancestor of our
BottomNavigationBar, then things would work as intended.
Ok Navigator, show me what you can do
The solution is to wrap the
body of our
Scaffold object with a new
But before we do that, let’s introduce thee new classes that we’ll be using to show our final UI.
The first class is called
How does this work?
- On lines 1–4, we define two route names:
- On line 7, we define the constructor for
TabNavigator. This takes a
- Note that
GlobalKey<NavigatorState>. We need this to uniquely identify the navigator across the entire app (read more about
- On line 22, we define a
_routeBuildersmethod, which associates a
WidgetBuilderto each of the two routes we have defined. We’ll look at the
ColorDetailPagein a second.
- On line 38, we implement the
build()method, which returns a new
- This takes a
- It also has an
onGenerateRoutemethod, which is called every time a route needs to be generated. This makes use of the
_routeBuilders()method we have defined above.
- On lines 11–19 we define a
_push()method which is used to push a detail route with a
Here is the
The purpose of this class is to show a
ListView with all the color shades of the input
MaterialColor is nothing more than a
ColorSwatchwith ten different shades.
For completeness, here is the
This one is simple: it just shows a page with an
AppBar and the color shade that is selected from the input
MaterialColor. It looks like this:
Putting things together
Now that we have our
TabNavigator, let’s go back to our
App and make use of it:
- First, we define a
- Then in our
build()method we create a
TabNavigatorwith it and also pass in the
If we run the app now, we can see that push works correctly when selecting a list item, and the
BottomNavigationBar stays in place. Yay! ?
There is one problem though. Switching between tabs doesn’t seem to work, as we always show the red pages inside the
This is because we have defined a new navigator, but this is shared across all three tabs.
Remember: what we want is independent navigation stacks for each tab!
Let’s fix this:
A few notes:
- On lines 9–13 we define a map of global navigator keys. This is what we need to ensure we use multiple navigators.
- The body of our
Scaffoldis now a
Stackwith three children.
- Each child is built in the
- This uses the
Offstagewidget with a child
offstageproperty is true if the tab being rendered doesn’t match the current tab.
- We pass
TabNavigatorto ensure that we have one separate navigator key for each tab.
If we compile and run the app, everything now works as intented. We can push/ pop each navigator independently, and the offstage navigators keep their state. ?
One more thing
If we run the app on Android, we observe an interesting behaviour when we press the back button:
The app is dismissed and we are back to the home screen!
This is because we haven’t specified how the back button should be handled.
Let’s fix that:
This is done with the
WillPopScope widget, which controls how routes are dismissed. From the documentation of
Registers a callback to veto attempts by the user to dismiss the enclosing /// [ModalRoute]
On line 4 we define a
onWillPop() callback to return false if the current navigator can pop, or true otherwise.
If we run the app again, we can see that pressing the back button dismisses any pushed routes, and only if we press it again we leave the app.
One thing to note is that when we push a new route on Android, this slides in from the bottom. Instead the convention is to slide in from the right on iOS.
Also, the transition on Android is a bit jittery for some reason. I’m not sure if this is an emulator issue and it looks ok on a real device.
Credits go to Brian Egan for finding a way to make the navigators work. It was his idea to use a
Offstage widgets to preserve the state of the navigators.
Today we have learned a good deal about Flutter navigation, and how to combine
Navigator widgets to enable multiple navigation stacks.
Offstage widgets ensures that all our navigators preserve their state as they remain inside the widget tree. This likely comes with some performance penalty, so I recommend to profile your app if you choose to use them.
The entire source code for this article can be found here:
nested-navigation-demo-flutter – Nested navigation with BottomNavigationBargithub.com
Please let me know in the comments if I have done something silly, or you know a better way of doing this. ?
For more articles and video tutorials, check out Coding With Flutter.
Learn to build iOS and Android apps with Dart and Flutter