How to create TabBar view in flutter with source code step wise

To create a TabBar view in Flutter where each tab displays different content and the tab’s color and text color change when selected, you can follow these steps. We’ll implement three tabs and customize their appearance and behavior.

Step-by-Step Guide to Creating a TabBar View in Flutter

Step 1: Set Up Your Flutter Project

First, make sure you have Flutter installed, and then create a new Flutter project:

flutter create tabbar_example
cd tabbar_example

Step 2: Update Dependencies (Optional)

For this example, we are using Flutter’s built-in widgets and do not need additional dependencies, so no changes are needed in the pubspec.yaml.

Step 3: Implement the TabBar in main.dart

Edit the lib/main.dart file to implement the TabBar and TabBarView. Here’s how to set it up:

import 'package:flutter/material.dart';

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

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

class TabBarExample extends StatefulWidget {
  @override
  _TabBarExampleState createState() => _TabBarExampleState();
}

class _TabBarExampleState extends State<TabBarExample> with SingleTickerProviderStateMixin {
  late TabController _tabController; // Initialize the tab controller

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this); // Set up the TabController with 3 tabs
  }

  @override
  void dispose() {
    _tabController.dispose(); // Dispose the controller when the widget is disposed
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('TabBar Example'),
        bottom: TabBar(
          controller: _tabController,
          indicatorColor: Colors.transparent, // Hides the bottom line indicator
          labelColor: Colors.white, // Color of the selected tab
          unselectedLabelColor: Colors.grey, // Color of the unselected tab
          tabs: [
            Tab(text: 'Tab 1'),
            Tab(text: 'Tab 2'),
            Tab(text: 'Tab 3'),
          ],
          onTap: (index) {
            setState(() {
              _tabController.index = index; // Changes the tab index on tap
            });
          },
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          _buildTabContent('Content for Tab 1', Colors.red),
          _buildTabContent('Content for Tab 2', Colors.green),
          _buildTabContent('Content for Tab 3', Colors.blue),
        ],
      ),
    );
  }

  Widget _buildTabContent(String text, Color color) {
    return Container(
      color: color,
      child: Center(
        child: Text(
          text,
          style: TextStyle(fontSize: 24, color: Colors.white),
        ),
      ),
    );
  }
}

Step 4: Explanation of the Code

  1. TabController Setup:
  • The TabController is initialized in the initState method with a length equal to the number of tabs (3 in this case).
  • The vsync parameter uses SingleTickerProviderStateMixin to ensure efficient resource management.
  1. AppBar with TabBar:
  • The AppBar widget includes a TabBar widget.
  • indicatorColor: Colors.transparent hides the bottom line indicator.
  • labelColor and unselectedLabelColor manage the text color for selected and unselected tabs.
  • The onTap method is used to handle tab changes manually if needed.
  1. TabBarView:
  • The TabBarView widget is used to display content corresponding to each tab.
  • It has the same controller as the TabBar to synchronize between tabs and views.
  • Each tab’s content is built using the _buildTabContent method, which shows different text and background colors for each tab.
  1. Changing Tab Text Color and Background:
  • The labelColor and unselectedLabelColor properties of the TabBar widget manage text color.
  • The TabBar changes the color of the selected and unselected tab texts.
  • The content changes with each tab click, and the background color changes based on the tab.
  1. Dispose Method:
  • The dispose method ensures that the TabController is properly disposed of when the widget is removed from the widget tree to avoid memory leaks.

Step 5: Run Your App

Run the Flutter app using:

flutter run

This will launch the app on your device or emulator. You should see a TabBar at the top with three tabs. Clicking each tab will display different content below the TabBar, and the tab’s color and text color will change according to its selected state.

Customization Tips

  • Change Tab Bar Color: Modify the color property of AppBar or use a Container to wrap the TabBar for more customization.
  • Add Icons to Tabs: You can add icons to the tabs by replacing Tab(text: 'Tab 1') with Tab(icon: Icon(Icons.home), text: 'Tab 1').
  • Customize Animation: Customize the tab change animation by using a custom PageController instead of TabController if needed.

By following these steps, you’ll create a Flutter app with a TabBar that has three tabs, each displaying different content, with customized colors and behaviors.

Related Articles

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top