Flutter TabBar & TabBarView Tutorial

In this tutorial, we will learn how to display a horizontal row of tabs and display a widget that corresponds to the currently selected tab.

To display a horizontal row of tabs, we can use TabBar widget.

To display a widget that corresponds to the currently selected tab, we can use TabBarView page view.

When we use TabBar and TabBarView, we should use a TabController to handle various aspects of a tab. In this tutorial, we shall use DefaultTabController, which makes our job easy for now. You can also use a custom TabController, but that requires additional inputs. Let us stick to DefaultTabController for this tutorial.

Example – Futter TabBar and TabBarView with DefaultTabController

Let us dive into an example Flutter Application and then dissect the code in our following discussion.

Create a basic Flutter Application in Android Studio or your favorite IDE and replace the main.dart file with the following code.

main.dart

</>
Copy
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Scaffold(
        appBar: AppBar(
          bottom: TabBar(
            tabs: [
              Tab(icon: Icon(Icons.android), text: "Tab 1",),
              Tab(icon: Icon(Icons.phone_iphone), text: "Tab 2"),
            ],
          ),
          title: Text('TutorialKart - TabBar & TabBarView'),
        ),
        body: TabBarView(
          children: [
            Center( child: Text("Page 1")),
            Center( child: Text("Page 2")),
          ],
        ),
      ),
    );
  }
}

Observe from the above code that

  • There are as many number of tabs in TabBar as that of children in TabBarView. And this number should match the length specified for DefaultTabController. Else you will get an error saying “Controller’s length property does not match the number of tabs present in TabBar’s tabs property.”.
  • DefaultTabController encloses TabBar and TabBarView.
  • For each tab in TabBar, you can specify either an icon or text or both. Atleast one of the icon and text is mandatory.

Output

Flutter TabBar & TabBarView Tutorial

Conclusion

In this Flutter Tutorial, we learned how to use TabBar and TabBarView with DefaultTabController.