DefaultTabController  widget and Attributes

DefaultTabController widget and Attributes

ยท

2 min read

The DefaultTabController widget in Flutter is a powerful tool for managing a tab-based user interface. It helps to synchronize the state of a TabBar and a TabBarView, ensuring that they work together seamlessly.

Key Attributes of the DefaultTabController Widget:

  1. length (int):

    • Specifies the number of tabs in the tab bar.
  2. child (Widget):

    • Represents the widget tree that the DefaultTabController manages.

Example Usage:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 3, // Number of tabs
        child: MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('DefaultTabController Example'),
        bottom: TabBar(
          tabs: [
            Tab(text: 'Tab 1'),
            Tab(text: 'Tab 2'),
            Tab(text: 'Tab 3'),
          ],
        ),
      ),
      body: TabBarView(
        children: [
          Center(child: Text('Tab 1 Content')),
          Center(child: Text('Tab 2 Content')),
          Center(child: Text('Tab 3 Content')),
        ],
      ),
    );
  }
}

In this example, we use the DefaultTabController widget to manage a TabBar and a corresponding TabBarView. The length attribute is set to 3, indicating that there are three tabs. The child attribute is set to the main content of the app, which includes an AppBar with a TabBar in the bottom attribute and a TabBarView displaying the content corresponding to each tab.

The DefaultTabController simplifies the synchronization between the TabBar and TabBarView, reducing the boilerplate code needed to handle tab-based navigation in a Flutter app.

Did you find this article valuable?

Support Vinit Mepani (Flutter Developer) by becoming a sponsor. Any amount is appreciated!

ย