Flutter Tabbar
A tab bar is a common UI pattern in mobile applications that allows users to switch between different screens or views. In Flutter, it is easy to implement a tab bar using the TabBar
and TabBarView
Widgets. This page will cover how to implement a basic tab bar in Flutter.
Syntax
Here is the basic syntax for creating a tab bar:
TabBar(
tabs: [
Tab(
text: 'Tab 1',
),
Tab(
text: 'Tab 2',
),
Tab(
text: 'Tab 3',
),
],
),
The TabBar
Widget takes a list of Tab
Widgets as children. Each Tab
can have an icon or text label.
Example
Here is an example of how to create a basic tab bar with two tabs:
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
title: Text('My Tabbed Page'),
bottom: TabBar(
tabs: [
Tab(text: 'Tab A'),
Tab(text: 'Tab B'),
],
),
),
body: TabBarView(
children: [
Center(child: Text('This is Tab A')),
Center(child: Text('This is Tab B')),
],
),
),
);
}
}
This code creates a basic tab bar with two tabs ('Tab A' and 'Tab B') and two corresponding views. The Center
Widgets are used to position the text in the center of the screen.
Output
The output of this code is a screen with a tab bar at the top and two tabs ('Tab A' and 'Tab B'). When the user taps on a tab, the corresponding view is displayed.
Explanation
This example demonstrates how to create a basic tab bar using the TabBar
and TabBarView
Widgets. The DefaultTabController
Widget is used to manage the state of the tabs. The TabBar
Widget determines the appearance and behavior of the tab bar itself. The TabBarView
Widget determines the contents of each tab.
Use
Developers can use the TabBar
and TabBarView
Widgets to create a variety of tabbed UIs, such as:
- Switching between different sections of an app
- Displaying multiple views of the same data
- Filtering or sorting large amounts of data
Important Points
- The
TabBar
andTabBarView
Widgets are easy to use and can save development time. - The
DefaultTabController
Widget should be used to manage the state of the tabs. - Developers can customize the appearance and behavior of the tab bar and its tabs using various properties and Widgets.
Summary
The TabBar
and TabBarView
Widgets are powerful tools for creating tabbed interfaces in Flutter. They are easy to use and can be customized in many ways to suit different needs and use cases. By managing the state of the tabs using DefaultTabController
, developers can create interactive UIs that let users switch between different views and sections of the app.