Introduction
Flutter is loaded with predefined components and bottom navigation bar is one of them. So, let’s see how can we implement a bottom navigation tab bar in Flutter.
Note
This article is one of the parts of my series Chat app in Flutter using Firebase. Our chat app series is one of the best examples to
make chat app in Flutter using Google Firebase. If you are interested in chat apps, you can check out the whole series.
Output
Steps
- The first and most basic step is to create a new application in Flutter. If you are a beginner, you can check my blog Create a first app in Flutter. I have created an app named “flutter_chat_app”.
- Create a new folder, "Pages" and in that, create a page named home.dart. On this page, we will generate the bottom navigation tab bar. So, we will put a button in the main.dart file which will navigate to the home.dart file. Below is the code for navigation from main.dart file to home.dart file.
- Navigator.of(context).pushReplacement(
- MaterialPageRoute(
- builder: (context) => HomePage(),
- ),
- );
- In home.dart file, create a class TabContent which contains the title and actual content of the tab. Check out the below class.
- class TabContent {
- String title;
- Widget content;
- TabContent({this.title, this.content});
- }
- Initialize an integer variable to track active tab index.
- Initialize the content of the tabs. For this example, we will take 2 tabs.
- List<TabContent> tabContent = [
- TabContent(
- title: 'Tab1',
- content: Center(
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- Text('Tab1'),
- ],
- ),
- ),
- ),
- TabContent(
- title: 'Tab2',
- content: Center(
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- Text('Tab2'),
- ],
- ),
- ),
- )
- ];
- Now, configure the bottom navigation tab bar in MaterialApp widget.
- return MaterialApp(
- home: DefaultTabController(
- length: 2,
- child: Scaffold(
- appBar: AppBar(
- title: Text(tabContent[_currentIndex].title),
- ),
- body: tabContent[_currentIndex].content,
- bottomNavigationBar: BottomNavigationBar(
- onTap: (index) {
- setState(
- () {
- _currentIndex = index;
- },
- );
- },
- currentIndex: _currentIndex,
- items: [
- new BottomNavigationBarItem(
- icon: Icon(Icons.mail),
- title: Text('Tab1'),
- ),
- new BottomNavigationBarItem(
- icon: Icon(Icons.verified_user),
- title: Text('Tab2'),
- )
- ],
- ),
- ),
- ),
- );
- Hurray!!! You are done with the sample building block of bottom navigation tab bar in Flutter. Run the program. Tweak the code and understand it in depth.
Conclusion
In this article, we have learned how we can implement the bottom navigation tab bar in Flutter. You can even customize and make it rich according to your requirements.