Working with tabs is a common pattern in apps following the Material Designguidelines. Flutter includes a convenient way to create tab layouts as part ofthe material library.

Directions

  • Create a TabController
  • Create the tabs
  • Create content for each tab

1. Create a TabController

In order for tabs to work, we’ll need to keep the selected tab and contentsections in sync. This is the job of theTabController.

We can either manually create a TabController or use theDefaultTabControllerWidget. Using the DefaultTabController is the simplest option, since it willcreate a TabController for us and make it available to all descendant Widgets.

  1. DefaultTabController(
  2. // The number of tabs / content sections we need to display
  3. length: 3,
  4. child: // See the next step!
  5. );

2. Create the tabs

Now that we have a TabController to work with, we can create our tabs usingthe TabBarWidget. In this example, we’ll create a TabBar with 3TabWidgets and place it within anAppBar.

  1. DefaultTabController(
  2. length: 3,
  3. child: Scaffold(
  4. appBar: AppBar(
  5. bottom: TabBar(
  6. tabs: [
  7. Tab(icon: Icon(Icons.directions_car)),
  8. Tab(icon: Icon(Icons.directions_transit)),
  9. Tab(icon: Icon(Icons.directions_bike)),
  10. ],
  11. ),
  12. ),
  13. ),
  14. );

By default, the TabBar looks up the Widget tree for the nearestDefaultTabController. If you’re manually creating a TabController, you’llneed to pass it to the TabBar.

3. Create content for each tab

Now that we have tabs, we’ll want to display content when a tab is selected.For this purpose, we’ll employ theTabBarView Widget.

Note: Order is important and must correspond to the order of the tabs in theTabBar!

  1. TabBarView(
  2. children: [
  3. Icon(Icons.directions_car),
  4. Icon(Icons.directions_transit),
  5. Icon(Icons.directions_bike),
  6. ],
  7. );

Complete example

  1. import 'package:flutter/material.dart';
  2. void main() {
  3. runApp(TabBarDemo());
  4. }
  5. class TabBarDemo extends StatelessWidget {
  6. @override
  7. Widget build(BuildContext context) {
  8. return MaterialApp(
  9. home: DefaultTabController(
  10. length: 3,
  11. child: Scaffold(
  12. appBar: AppBar(
  13. bottom: TabBar(
  14. tabs: [
  15. Tab(icon: Icon(Icons.directions_car)),
  16. Tab(icon: Icon(Icons.directions_transit)),
  17. Tab(icon: Icon(Icons.directions_bike)),
  18. ],
  19. ),
  20. title: Text('Tabs Demo'),
  21. ),
  22. body: TabBarView(
  23. children: [
  24. Icon(Icons.directions_car),
  25. Icon(Icons.directions_transit),
  26. Icon(Icons.directions_bike),
  27. ],
  28. ),
  29. ),
  30. ),
  31. );
  32. }
  33. }

Tabs Demo