IndexedStack with BottomNavigationBar

Pouya Amirahmadi
2 min readOct 8, 2020

We’ve demonstrated how to keep page state using BottomNavigationBar and PageStorage in the previous article, but in this article, we will talk about the IndexedStack widget, how it’s gonna solve the problem.

Let’s see what the Flutter document says about IndexedWidget:

A Stack that shows a single child from a list of children.

So What does it mean? Essentially it means, users can switch between widgets, without losing states.

So let’s see how we can achieve our goal, i.e let the user navigate between widgets using BottomNavigationBar and keep page state.

To show that, 2 pages are built, one is the sample flutter page that you can increase the number shown on screen and another one is a form in which the user can enter their personal information.

As it seems it’s a simple code that using MaterialApp and passing a Home widget as its home parameters.

So let’s break down our Home widget and see how it’s implemented:

Line 2: define a variable called selectedIdx, which is supposed to hold the current index.

Line 4–17: Here we define our BottomNavBarItemData so that later on it’s been used to create the bottom navigation bar items.

So up to now, nothing new. right? shall we see how the Home body is created?

So basically, we created a Scaffold widget that has 2 parameters, i.e bottomNavigationBar and body.

Line 5–16: A BottomNavigationBar just created a here, that its items are built with the provided items and simply whenever every item is clicked, our selectedIdx gets updated

Line 19–26: A IndexedWidget is provided for BottomNavigationBar body parameter. IndexedWidget needs at least two parameters provided, index and children. the index simply tells the widget which child needs to be shown and the children is simply a list of widgets that needs to be shown.

So what happens here is, whenever the user clicks one of the bottom navigation bar items, the selectedIdx gets updated furthermore IndexedStack knows which widget gets on top of the stack and saves the state of the previous one.

You can find the Github repository here if you want to take look at the source code

Thanks!

--

--