Flutter: TabBar and TabBarView Usage
personAhmet Balaman
calendar_today
FlutterTabBarTabsNavigationWidgetUI
Using TabBar and TabBarView, we can show multiple pages on the same screen. We can switch between pages by tapping on tabs or swiping left-right with finger gestures.
Live Demo
You can try this widget in the interactive example below:
💡 If the example above doesn't load, click DartPad to run it in a new tab.
Basic Usage
A TabController is required to use TabBar:
class MyPage extends StatefulWidget {
@override
State<MyPage> createState() => _MyPageState();
}
class _MyPageState extends State<MyPage> with SingleTickerProviderStateMixin {
late TabController _tabController;
@override
void initState() {
super.initState();
_tabController = TabController(length: 3, vsync: this);
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Tabs'),
bottom: TabBar(
controller: _tabController,
tabs: [
Tab(text: 'Tab 1'),
Tab(text: 'Tab 2'),
Tab(text: 'Tab 3'),
],
),
),
body: TabBarView(
controller: _tabController,
children: [
Center(child: Text('Page 1')),
Center(child: Text('Page 2')),
Center(child: Text('Page 3')),
],
),
);
}
}Simple Usage with DefaultTabController
DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabs: [
Tab(icon: Icon(Icons.home)),
Tab(icon: Icon(Icons.search)),
Tab(icon: Icon(Icons.person)),
],
),
),
body: TabBarView(
children: [
HomeTab(),
SearchTab(),
ProfileTab(),
],
),
),
)TabBar Properties
| Property | Description |
|---|---|
tabs |
List of Tab widgets |
controller |
TabController |
indicatorColor |
Underline color |
indicatorWeight |
Underline thickness |
labelColor |
Selected tab color |
unselectedLabelColor |
Unselected tab color |
isScrollable |
Scrollable tabs |
Tab with Icon and Text
Tab(
icon: Icon(Icons.home),
text: 'Home',
)
// Icon only
Tab(icon: Icon(Icons.search))
// Text only
Tab(text: 'Profile')Programmatic Tab Switching
// Go to specific tab
_tabController.animateTo(2);
// Get current index
int currentIndex = _tabController.index;
// Listen to tab changes
_tabController.addListener(() {
print('Active tab: ${_tabController.index}');
});Scrollable Tabs
When there are many tabs:
TabBar(
isScrollable: true, // Horizontal scrolling enabled
tabs: [
Tab(text: 'Tab 1'),
Tab(text: 'Tab 2'),
Tab(text: 'Tab 3'),
Tab(text: 'Tab 4'),
Tab(text: 'Tab 5'),
],
)Summary
- TabBar: Shows tab buttons
- TabBarView: Shows tab contents
- TabController: Manages tab state
- SingleTickerProviderStateMixin: Required for animation
- DefaultTabController: Wrapper for simple usage
Tabs are ideal for showing multiple content on the same screen.