Flutter : Persistent Tab bars

Diego Velasquez
3 min readJul 7, 2018

--

When I was migrating to Flutter an application from the company where I work.
This app has a screen which contains a tab bar with multiple screens, I ran into a problem, when I select a tab, the screen reload each time I changed, and this is not the behavior that we had in the native apps.

I’m going to write a simple problem to recreate the situation and we’ll try to solve it.

Let’s code

We are going to create a screen with 2 tabs, in Flutter it is very easy compared to Android or iOS.

Let us begin:

Done, we have a screen with 2 tabs, the header of each tab has an icon and a title, and these contain a different text on each screen.

This is the simplest way to create a screen with tabs in Flutter, now we go step by step.

DefaultTabController

Allows you to define a Tabs controller Widget, which works in conjunction with TabBar and TabBarView.
This controller has an attribute called length that identifies the number of Tabs it contains.

TabBar

Allows you to create the tabs that go in the header/footer, it has an attribute called tabs that receives a list of widgets of type Tab.

TabBarView

Allows you to create the widgets that will go inside each tab in the children attribute.

The number of Tabs and Widgets within TabBarView must be equal to the “length” attribute defined in the controller

I will proceed to replace the widgets of each Tab with screens that I already have, each screen consumes a Rest web service and shows a list, the code would be as follows

And this is the result

Do you notice something different?

That’s right, the content of Tab 1 is reloaded each time it is selected.

And what happened to Tab 2? Why does it keep the content and not load it again?

This is due to the use of the mixin and AutomaticKeepAliveClientMixin on our State.

class _Page2State extends State<Page2> with AutomaticKeepAliveClientMixin<Page2> {

When we use this class, we must implement the following method

@override
bool get wantKeepAlive => true;

On Page2 we are using the mixin and returning true, indicating that we want to maintain the content of the page, so every time the Tab is selected, the initState method is only executed once, at the time of creation.

In the case of Page1, we are not using the mixin, so every time the tab is selected, enter initState and reload the content.

You can check the source code in my flutter-samples repo https://github.com/diegoveloper/flutter-samples

Conclusion

We saw how easy it is to create tabs in Flutter, and we were able to maintain the content every time we entered a Tab, in case the application requires it.
And you, what other way do you use to keep the content on the screen?

References

https://www.dartlang.org/articles/language/mixins
https://docs.flutter.io/flutter/material/DefaultTabController-class.html

--

--