In this article, we’re going to learn how to implement Flutter TabBar with an example.
What you’ll learn?
- How to create a TabBar
- Switching between tabs
- change the background color for the flutter tab bar
How to create Tabbar in Flutter?
To implement a tab bar in a flutter, we’re going to use widgets called DefaultTabController, TabBarView, and Tab.
import 'package:flutter/material.dart';
class TabbarExample extends StatefulWidget {
const TabbarExample({Key? key}) : super(key: key);
@override
State<TabbarExample> createState() => _TabbarExampleState();
}
class _TabbarExampleState extends State<TabbarExample> {
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
title: const Text("AppMaking.com"),
backgroundColor: Colors.blueGrey[900],
bottom: const TabBar(
tabs: [
Tab(
icon: Icon(Icons.chat_bubble),
text: "Chats",
),
Tab(
icon: Icon(Icons.video_call),
text: "Calls",
),
Tab(
icon: Icon(Icons.settings),
text: "Settings",
)
],
),
),
body: const TabBarView(
children: [
Center(
child: Text("Chats"),
),
Center(
child: Text("Calls"),
),
Center(
child: Text("Settings"),
),
],
),
),
);
}
}
Code Explanation:
- DefaultTabController is used to control the navigation between tabs, we’re setting the default length is 3 which means, we’re declaring 3 tabs
- Inside the App bar bottom, we are declaring Tabbar widget which has 3 Tab widget
- Inside the Scaffold body, we are having TabBarView which is containing 3 pages
How to change the background color for the flutter TabBar?
In order to change the TabBar background color, you just need to add background color for AppBar
Flutter Tabbar Example output
Reference:
- https://api.flutter.dev/flutter/material/TabBar-class.html
- https://api.flutter.dev/flutter/material/TabBarView-class.html