TabBar class
A Material Design primary tab bar.
Primary tabs are placed at the top of the content pane under a top app bar. They display the main content destinations.
Typically created as the AppBar.bottom part of an AppBar and in conjunction with a TabBarView.
Learn more about TabBar on the Flutter YouTube channel.
If a TabController is not provided, then a DefaultTabController ancestor must be provided instead. The tab controller's TabController.length must equal the length of the tabs list and the length of the TabBarView.children list.
Requires one of its ancestors to be a Material widget.
Uses values from TabBarThemeData if it is set in the current context.
This sample shows the implementation of TabBar and TabBarView using a DefaultTabController. Each Tab corresponds to a child of the TabBarView in the order they are written.
To see it in action, copy and run this code snippet on DartPad.
import 'package:material_ui/material_ui.dart';
/// Flutter code sample for [TabBar].
void main() => runApp(const TabBarApp());
class TabBarApp extends StatelessWidget {
const TabBarApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: TabBarExample());
}
}
class TabBarExample extends StatelessWidget {
const TabBarExample({super.key});
@override
Widget build(BuildContext context) {
return DefaultTabController(
initialIndex: 1,
length: 3,
child: Scaffold(
appBar: AppBar(
title: const Text('TabBar Sample'),
bottom: const TabBar(
tabs: <Widget>[
Tab(icon: Icon(Icons.cloud_outlined)),
Tab(icon: Icon(Icons.beach_access_sharp)),
Tab(icon: Icon(Icons.brightness_5_sharp)),
],
),
),
body: const TabBarView(
children: <Widget>[
Center(child: Text("It's cloudy here")),
Center(child: Text("It's rainy here")),
Center(child: Text("It's sunny here")),
],
),
),
);
}
}
TabBar can also be implemented by using a TabController which provides more options to control the behavior of the TabBar and TabBarView. This can be used instead of a DefaultTabController, demonstrated below.
To see it in action, copy and run this code snippet on DartPad.
import 'package:material_ui/material_ui.dart';
/// Flutter code sample for [TabBar].
void main() => runApp(const TabBarApp());
class TabBarApp extends StatelessWidget {
const TabBarApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: TabBarExample());
}
}
class TabBarExample extends StatefulWidget {
const TabBarExample({super.key});
@override
State<TabBarExample> createState() => _TabBarExampleState();
}
/// [AnimationController]s can be created with `vsync: this` because of
/// [TickerProviderStateMixin].
class _TabBarExampleState extends State<TabBarExample>
with TickerProviderStateMixin {
late final 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: const Text('TabBar Sample'),
bottom: TabBar(
controller: _tabController,
tabs: const <Widget>[
Tab(icon: Icon(Icons.cloud_outlined)),
Tab(icon: Icon(Icons.beach_access_sharp)),
Tab(icon: Icon(Icons.brightness_5_sharp)),
],
),
),
body: TabBarView(
controller: _tabController,
children: const <Widget>[
Center(child: Text("It's cloudy here")),
Center(child: Text("It's rainy here")),
Center(child: Text("It's sunny here")),
],
),
);
}
}
This sample showcases nested Material 3 TabBars. It consists of a primary TabBar with nested a secondary TabBar. The primary TabBar uses a DefaultTabController while the secondary TabBar uses a TabController.
To see it in action, copy and run this code snippet on DartPad.
import 'package:material_ui/material_ui.dart';
/// Flutter code sample for [TabBar].
void main() => runApp(const TabBarApp());
class TabBarApp extends StatelessWidget {
const TabBarApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: TabBarExample());
}
}
class TabBarExample extends StatelessWidget {
const TabBarExample({super.key});
@override
Widget build(BuildContext context) {
return DefaultTabController(
initialIndex: 1,
length: 3,
child: Scaffold(
appBar: AppBar(
title: const Text('Primary and secondary TabBar'),
bottom: const TabBar(
dividerColor: Colors.transparent,
tabs: <Widget>[
Tab(text: 'Flights', icon: Icon(Icons.flight)),
Tab(text: 'Trips', icon: Icon(Icons.luggage)),
Tab(text: 'Explore', icon: Icon(Icons.explore)),
],
),
),
body: const TabBarView(
children: <Widget>[
NestedTabBar('Flights'),
NestedTabBar('Trips'),
NestedTabBar('Explore'),
],
),
),
);
}
}
class NestedTabBar extends StatefulWidget {
const NestedTabBar(this.outerTab, {super.key});
final String outerTab;
@override
State<NestedTabBar> createState() => _NestedTabBarState();
}
class _NestedTabBarState extends State<NestedTabBar>
with TickerProviderStateMixin {
late final TabController _tabController;
@override
void initState() {
super.initState();
_tabController = TabController(length: 2, vsync: this);
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
TabBar.secondary(
controller: _tabController,
tabs: const <Widget>[
Tab(text: 'Overview'),
Tab(text: 'Specifications'),
],
),
Expanded(
child: TabBarView(
controller: _tabController,
children: <Widget>[
Card(
margin: const .all(16.0),
child: Center(child: Text('${widget.outerTab}: Overview tab')),
),
Card(
margin: const .all(16.0),
child: Center(
child: Text('${widget.outerTab}: Specifications tab'),
),
),
],
),
),
],
);
}
}
This sample showcases how to apply custom behavior based on the scroll in TabBar. It utilizes scroll notifications (ScrollMetricsNotification and ScrollNotification) within NotificationListener callback to monitor the scroll offset, allowing for interface customization based on the obtained offset.
To see it in action, copy and run this code snippet on DartPad.
import 'package:material_ui/material_ui.dart';
/// Flutter code sample for a [TabBar] that displays custom effects on top of
/// the tab bar itself when there are more tabs in the scroll direction.
void main() => runApp(const TabBarApp());
class TabBarApp extends StatelessWidget {
const TabBarApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: TabBarExample());
}
}
class TabBarExample extends StatefulWidget {
const TabBarExample({super.key});
@override
State<TabBarExample> createState() => _TabBarExampleState();
}
class _TabBarExampleState extends State<TabBarExample> {
double scrollOffset = 0;
double maxScrollExtent = 0;
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 20,
child: Scaffold(
appBar: AppBar(
title: const Text('TabBar with scroll notifications'),
bottom: PreferredSize(
preferredSize: const Size.fromHeight(56.0),
child: NotificationListener<Notification>(
onNotification: (Notification notification) {
// ScrollMetricsNotification is for initial layout.
// ScrollNotification is for real-time scroll updates.
final ScrollMetrics? metrics = switch (notification) {
ScrollMetricsNotification(:final metrics) => metrics,
ScrollNotification(:final metrics) => metrics,
_ => null,
};
if (metrics != null) {
setState(() {
scrollOffset = metrics.pixels;
maxScrollExtent = metrics.maxScrollExtent;
});
}
return false;
},
child: Stack(
children: [
TabBar(
isScrollable: true,
tabs: List<Widget>.generate(
20,
(int index) => Tab(text: 'Tab $index'),
),
),
// When the selected tab is not at the beginning or end
// (indicating TabBar is scrollable), add a gradient mask
// to left or right.
Positioned(
top: 0,
bottom: 0,
left: 0,
right: 0,
child: GradientMasks(
scrollOffset: scrollOffset,
maxScrollExtent: maxScrollExtent,
),
),
],
),
),
),
),
),
);
}
}
class GradientMasks extends StatelessWidget {
final double scrollOffset;
final double maxScrollExtent;
const GradientMasks({
super.key,
required this.scrollOffset,
required this.maxScrollExtent,
});
@override
Widget build(BuildContext context) {
return Row(
children: [
if (scrollOffset > 0) const LeftMask(),
const Spacer(),
if (scrollOffset < maxScrollExtent) const RightMask(),
],
);
}
}
/// This mask shows when the selected tab is not at the beginning.
class LeftMask extends StatelessWidget {
const LeftMask({super.key});
@override
Widget build(BuildContext context) {
return IgnorePointer(
child: ClipRect(
child: BackdropFilter(
filter: ColorFilter.mode(
Colors.black.withValues(alpha: 0.2),
BlendMode.srcOver,
),
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: [
Colors.white.withValues(alpha: 0.8),
Colors.white.withValues(alpha: 0.2),
],
),
),
child: Align(
alignment: .centerLeft,
child: Padding(
padding: .only(left: 4),
child: Icon(
Icons.chevron_left,
color: Colors.black.withValues(alpha: 0.4),
),
),
),
),
),
),
);
}
}
/// This mask shows when the selected tab is not at the end.
class RightMask extends StatelessWidget {
const RightMask({super.key});
@override
Widget build(BuildContext context) {
return IgnorePointer(
child: ClipRect(
child: BackdropFilter(
filter: ColorFilter.mode(
Colors.black.withValues(alpha: 0.2),
BlendMode.srcOver,
),
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.centerRight,
end: Alignment.centerLeft,
colors: [
Colors.white.withValues(alpha: 0.8),
Colors.white.withValues(alpha: 0.2),
],
),
),
child: Align(
alignment: .centerRight,
child: Padding(
padding: .only(right: 4),
child: Icon(
Icons.chevron_right,
color: Colors.black.withValues(alpha: 0.4),
),
),
),
),
),
),
);
}
}
See also:
- TabBar.secondary, for a secondary tab bar.
- TabBarView, which displays page views that correspond to each tab.
- TabController, which coordinates tab selection between a TabBar and a TabBarView.
- https://m3.material.io/components/tabs/overview, the Material 3 tab bar specification.
- Inheritance
- Implemented types
Constructors
-
TabBar({Key? key, required List<
Widget> tabs, TabController? controller, TabBarScrollController? scrollController, bool isScrollable = false, EdgeInsetsGeometry? padding, Color? indicatorColor, bool automaticIndicatorColorAdjustment = true, double indicatorWeight = 2.0, EdgeInsetsGeometry indicatorPadding = EdgeInsets.zero, Decoration? indicator, TabBarIndicatorSize? indicatorSize, Color? dividerColor, double? dividerHeight, Color? labelColor, TextStyle? labelStyle, EdgeInsetsGeometry? labelPadding, Color? unselectedLabelColor, TextStyle? unselectedLabelStyle, DragStartBehavior dragStartBehavior = DragStartBehavior.start, WidgetStateProperty<Color?> ? overlayColor, MouseCursor? mouseCursor, bool? enableFeedback, ValueChanged<int> ? onTap, TabValueChanged<bool> ? onHover, TabValueChanged<bool> ? onFocusChange, ScrollPhysics? physics, InteractiveInkFeatureFactory? splashFactory, BorderRadius? splashBorderRadius, TabAlignment? tabAlignment, TextScaler? textScaler, TabIndicatorAnimation? indicatorAnimation}) -
Creates a Material Design primary tab bar.
const
-
TabBar.secondary({Key? key, required List<
Widget> tabs, TabController? controller, TabBarScrollController? scrollController, bool isScrollable = false, EdgeInsetsGeometry? padding, Color? indicatorColor, bool automaticIndicatorColorAdjustment = true, double indicatorWeight = 2.0, EdgeInsetsGeometry indicatorPadding = EdgeInsets.zero, Decoration? indicator, TabBarIndicatorSize? indicatorSize, Color? dividerColor, double? dividerHeight, Color? labelColor, TextStyle? labelStyle, EdgeInsetsGeometry? labelPadding, Color? unselectedLabelColor, TextStyle? unselectedLabelStyle, DragStartBehavior dragStartBehavior = DragStartBehavior.start, WidgetStateProperty<Color?> ? overlayColor, MouseCursor? mouseCursor, bool? enableFeedback, ValueChanged<int> ? onTap, TabValueChanged<bool> ? onHover, TabValueChanged<bool> ? onFocusChange, ScrollPhysics? physics, InteractiveInkFeatureFactory? splashFactory, BorderRadius? splashBorderRadius, TabAlignment? tabAlignment, TextScaler? textScaler, TabIndicatorAnimation? indicatorAnimation}) -
Creates a Material Design secondary tab bar.
const
Properties
- automaticIndicatorColorAdjustment → bool
-
Whether this tab bar should automatically adjust the indicatorColor.
final
- controller → TabController?
-
This widget's selection and animation state.
final
- dividerColor → Color?
-
The color of the divider.
final
- dividerHeight → double?
-
The height of the divider.
final
- dragStartBehavior → DragStartBehavior
-
Determines the way that drag start behavior is handled.
final
- enableFeedback → bool?
-
Whether detected gestures should provide acoustic and/or haptic feedback.
final
- hashCode → int
-
The hash code for this object.
no setterinherited
- indicator → Decoration?
-
Defines the appearance of the selected tab indicator.
final
- indicatorAnimation → TabIndicatorAnimation?
-
Specifies the animation behavior of the tab indicator.
final
- indicatorColor → Color?
-
The color of the line that appears below the selected tab.
final
- indicatorPadding → EdgeInsetsGeometry
-
The padding for the indicator.
final
- indicatorSize → TabBarIndicatorSize?
-
Defines how the selected tab indicator's size is computed.
final
- indicatorWeight → double
-
The thickness of the line that appears below the selected tab.
final
- isScrollable → bool
-
Whether this tab bar can be scrolled horizontally.
final
- key → Key?
-
Controls how one widget replaces another widget in the tree.
finalinherited
- labelColor → Color?
-
The color of selected tab labels.
final
- labelPadding → EdgeInsetsGeometry?
-
The padding added to each of the tab labels.
final
- labelStyle → TextStyle?
-
The text style of the selected tab labels.
final
- mouseCursor → MouseCursor?
-
The cursor for a mouse pointer when it enters or is hovering over the
individual tab widgets.
final
-
onFocusChange
→ TabValueChanged<
bool> ? -
An optional callback that's called when a Tab's focus state in the
TabBar changes.
final
-
onHover
→ TabValueChanged<
bool> ? -
An optional callback that's called when a Tab's hover state in the
TabBar changes.
final
-
onTap
→ ValueChanged<
int> ? -
An optional callback that's called when the TabBar is tapped.
final
-
overlayColor
→ WidgetStateProperty<
Color?> ? -
Defines the ink response focus, hover, and splash colors.
final
- padding → EdgeInsetsGeometry?
-
The amount of space by which to inset the tab bar.
final
- physics → ScrollPhysics?
-
How the TabBar's scroll view should respond to user input.
final
- preferredSize → Size
-
A size whose height depends on if the tabs have both icons and text.
no setteroverride
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
- scrollController → TabBarScrollController?
-
The TabBarScrollController for this TabBar.
final
- splashBorderRadius → BorderRadius?
-
Defines the clipping radius of splashes that extend outside the bounds of the tab.
final
- splashFactory → InteractiveInkFeatureFactory?
-
Creates the tab bar's InkWell splash factory, which defines
the appearance of "ink" splashes that occur in response to taps.
final
- tabAlignment → TabAlignment?
-
Specifies the horizontal alignment of the tabs within a TabBar.
final
- tabHasTextAndIcon → bool
-
Returns whether the TabBar contains a tab with both text and icon.
no setter
-
tabs
→ List<
Widget> -
Typically a list of two or more Tab widgets.
final
- textScaler → TextScaler?
-
Specifies the text scaling behavior for the Tab label.
final
- unselectedLabelColor → Color?
-
The color of unselected tab labels.
final
- unselectedLabelStyle → TextStyle?
-
The text style of the unselected tab labels.
final
Methods
-
createElement(
) → StatefulElement -
Creates a StatefulElement to manage this widget's location in the tree.
inherited
-
createState(
) → State< TabBar> -
Creates the mutable state for this widget at a given location in the tree.
override
-
debugDescribeChildren(
) → List< DiagnosticsNode> -
Returns a list of DiagnosticsNode objects describing this node's
children.
inherited
-
debugFillProperties(
DiagnosticPropertiesBuilder properties) → void -
Add additional properties associated with the node.
inherited
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
toDiagnosticsNode(
{String? name, DiagnosticsTreeStyle? style}) → DiagnosticsNode -
Returns a debug representation of the object that is used by debugging
tools and by DiagnosticsNode.toStringDeep.
inherited
-
toString(
{DiagnosticLevel minLevel = DiagnosticLevel.info}) → String -
A string representation of this object.
inherited
-
toStringDeep(
{String prefixLineOne = '', String? prefixOtherLines, DiagnosticLevel minLevel = DiagnosticLevel.debug, int wrapWidth = 65}) → String -
Returns a string representation of this node and its descendants.
inherited
-
toStringShallow(
{String joiner = ', ', DiagnosticLevel minLevel = DiagnosticLevel.debug}) → String -
Returns a one-line detailed description of the object.
inherited
-
toStringShort(
) → String -
A short, textual description of this widget.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited