Flutter TabBar & TabBarView: Displaying Tabs and Corresponding Widgets

In this tutorial, we will explore how to display a horizontal row of tabs and corresponding widgets in Flutter using the TabBar and TabBarView widgets. We will use the DefaultTabController to handle various aspects of a tab, making our job easy. 

The tutorial includes an example Flutter application, code dissection, and observations. By the end of this tutorial, you will know how to implement the TabBar and TabBarView widgets in your Flutter application.

By following these steps, you can easily implement the TabBar and TabBarView widgets in your Flutter application.

  • Import the necessary packages:
  • Wrap your widget tree with a DefaultTabController widget, which provides the necessary state management for the TabBar and TabBarView widgets:


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")),
      ],
    ),
  ),
)

  • Specify the number of tabs you want in your TabBar widget and the corresponding widgets in your TabBarView widget. The number of tabs should match the length property specified in the DefaultTabController. In the example above, we have two tabs and two corresponding widgets.
  • Optionally, you can specify icons or text or both for each tab in the TabBar widget. At least one of the icon and text is mandatory.
  • Customize the appearance and behavior of the TabBar and TabBarView widgets to suit your needs. For example, you can change the colors, fonts, and animations used in the widgets.

..

Full code:



import 'package:flutter/material.dart';

class BasicTabDemo extends StatefulWidget {
  const BasicTabDemo({super.key});

  @override
  BasicTabDemoState createState() => BasicTabDemoState();
}

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

..



Comments