Working with Tabs

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.

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

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.

DefaultTabController(
  length: 3,
  child: Scaffold(
    appBar: AppBar(
      bottom: TabBar(
        tabs: [
          Tab(icon: Icon(Icons.directions_car)),
          Tab(icon: Icon(Icons.directions_transit)),
          Tab(icon: Icon(Icons.directions_bike)),
        ],
      ),
    ),
  ),
);

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!

TabBarView(
  children: [
    Icon(Icons.directions_car),
    Icon(Icons.directions_transit),
    Icon(Icons.directions_bike),
  ],
);

Complete example

import 'package:flutter/material.dart';

void main() {
  runApp(TabBarDemo());
}

class TabBarDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 3,
        child: Scaffold(
          appBar: AppBar(
            bottom: TabBar(
              tabs: [
                Tab(icon: Icon(Icons.directions_car)),
                Tab(icon: Icon(Icons.directions_transit)),
                Tab(icon: Icon(Icons.directions_bike)),
              ],
            ),
            title: Text('Tabs Demo'),
          ),
          body: TabBarView(
            children: [
              Icon(Icons.directions_car),
              Icon(Icons.directions_transit),
              Icon(Icons.directions_bike),
            ],
          ),
        ),
      ),
    );
  }
}

Tabs Demo