Tabs are the part of the UI that navigates the user through different routes(ie, pages) when clicked upon. The use of tabs in applications is standard practice. Flutter provides a simple way to create tab layouts using the material library. In this article, we will be exploring the same in detail.
To understand the concept of tabs and their functionality in a Flutter app, let's build a simple app with 5 tabs by following the below steps:
Steps to Implement the tabs in Flutter Application
Step 1 : Designing a TabController
The TabController as the name suggests controls the functioning of each tab by syncing the tabs and the contents with each other. The DefaultTabController widget is one of the simplest ways to create tabs in flutter. It is done as shown below:
DefaultTabController(
// total 5 tabs
length: 5,
child: //code
);
Step 2 : Adding tabs
A tab in Flutter can be created using a TabBar widget as shown below:
home: DefaultTabController(
length: 5,
child: Scaffold(
appBar: AppBar(
bottom: const TabBar(
tabs: [
Tab(icon: Icon(Icons.music_note)),
Tab(icon: Icon(Icons.music_video)),
Tab(icon: Icon(Icons.camera_alt)),
Tab(icon: Icon(Icons.grade)),
Tab(icon: Icon(Icons.email)),
],
), //TabBar
)
)
To know more about Appbar in flutter refer this article : Flutter – AppBar Widget
Step 3 : Adding content to tabs
The TabBarView widget can be used to specify the contents of each tab. For the sake of simplicity we will display the icons in the tab as the content of the tab as shown below:
body: const TabBarView(
children: [
Icon(Icons.music_note),
Icon(Icons.music_video),
Icon(Icons.camera_alt),
Icon(Icons.grade),
Icon(Icons.email),
],
), // TabBarView
)
Complete Source Code
main.dart:
import 'package:flutter/material.dart';
// function to trigger the app build
void main() {
runApp(const TabBarDemo());
}
// class to build the app
class TabBarDemo extends StatelessWidget {
const TabBarDemo({Key? key}) : super(key: key);
// build the app
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 5,
child: Scaffold(
appBar: AppBar(
foregroundColor: Colors.white,
bottom: const TabBar(
indicatorColor: Colors.white,
unselectedLabelColor: Colors.white,
labelColor: Colors.white,
tabs: [
Tab(icon: Icon(Icons.music_note)),
Tab(icon: Icon(Icons.music_video)),
Tab(icon: Icon(Icons.camera_alt)),
Tab(icon: Icon(Icons.grade)),
Tab(icon: Icon(Icons.email)),
],
), // TabBar
title: const Text('GeeksForGeeks'),
backgroundColor: Colors.green,
), // AppBar
body: const TabBarView(
children: [
Icon(Icons.music_note),
Icon(Icons.music_video),
Icon(Icons.camera_alt),
Icon(Icons.grade),
Icon(Icons.email),
],
), // TabBarView
), // Scaffold
), // DefaultTabController
); // MaterialApp
}
}