Flutter Series #3 - How to Build Tab Bar and Display Content in Flutter

in #flutter4 hours ago

Hello everyone!

flutter tab bar.png

Designed with Canva

Today we will learn how to create a Tab Bar in Flutter and display data in each tab of the tab bar.


image.png

I have created a project and then I created a new screen with the name Home Screen. I have connected HomScreen with the main.dart file as an initial route. In the home screen I have taken a stateless widget. Now in this stateless widget we will develop tab bar. We know that tab bar is very essential part of many applications. The biggest example of tab bar usage is its use in the whatsapp that is a global social media application.


image.png

I have wrapped Scaffold widget with the DefaultTabController widget to implement Tab Bar. In the DefaultTabController we have to define the length or the number of tabs that we are going to create. I have defined to create 4 tabs in the tab bar. We know that Tab Bar is the part of the App Bar so we need to make the app bar first. At the bottom of the app bar tab bar will appear.

I have created the app bar and I gave it some styling to make it look beautiful and attractive. Then I used bottom property of the app bar to use Tab Bar. This tab bar expects tabs in the form of the children. In the children we can use any widget such as Text, or Icon. Keep in mind to create same number of tabs as you have defined as length in the DefaultTabController otherwise it will through an error.


image.png

This is the output of the code which we have written so far. We have learnt to create the app bar and tab bar in the app bar so far. Now we will implement view of these tabs or data of these tabs in the body. Currently data is not linked with these tabs of the tab bar.


image.png

AS the data is displayed in the body so there is a specific widget in the body of the Scaffold. I have used body property and passed TabBarView to display the data of the tabs. For only understanding purpose I have used simple texts to display on the screen. One thing to keep in mind is that in the current scenario in the tab bar view we have to consider the order of the content according the order of the tabs in the tab bar.


image.png

This is the final tab bar view after adding the indicator colour. This is a simple code and it can be made more simple by removing the redundant code but for the beginners this is enough to understand. In the upcoming learning class I will combine both things that we have explored so far which are tab bar and drawer.


tabbar-ezgif.com-resize.gif

Here you can see the dynamic app bar of the application. As the tab changes the content body also changes.

How to Build a Beautiful and Functional App Drawer in Flutter with User Account Header
How to develop a Lottery App in Flutter with Game History