Mastering TabBar and TabBarView Implementation in Flutter: A Comprehensive Guide for 2023

5 min read

Flutter, with its powerful set of widgets, offers an excellent framework for building visually appealing and efficient user interfaces. One standout feature that contributes to seamless app navigation and organization is the combination of TabBar and TabBarView. In this comprehensive guide, we will walk you through the step-by-step process of implementing and mastering TabBar and TabBarView in your Flutter app. We will also explore various customization options and best practices to keep your app up-to-date in 2023.

Setting up TabBar in Flutter

To get started, let’s lay the foundation for integrating TabBar into your Flutter app. We’ll create a basic example with three tabs:

Copy
import 'package:flutter/material.dart';

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

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

How to Customize the Tab Indicator in TabBar

Tab Color

You can set the color of the selected and unselected tabs using the 'indicatorColor' and 'unselectedLabelColor' properties of the 'TabBar' widget. For instance:

Copy
TabBar(
  indicatorColor: Colors.blue,
  unselectedLabelColor: Colors.grey,
  tabs: [...],
),

Tab Size

You can adjust the size of the tabs using the 'labelPadding' property. For example:

Copy
TabBar(
  labelPadding: EdgeInsets.symmetric(
    horizontal: 16.0,
  ),
  tabs: [...],
),

Tab Height

Modify the height of the tabs using the 'indicatorWeight' property:

Copy
TabBar(
  indicatorWeight: 3.0,
  tabs: [...],
),

Change the Indicator

Customize the appearance of the tab indicator using the 'indicator' property. You can create your own 'BoxDecoration' for a unique look:

Copy
TabBar(
  indicator: BoxDecoration(
    color: Colors.orange,
    borderRadius: BorderRadius.circular(8.0),
  ),
  tabs: [...],
),

TabBar Background Color

You can alter the background color of the 'TabBar' using the 'backgroundColor' property:

Copy
TabBar(
  backgroundColor: Colors.grey[200],
  tabs: [...],
),

Background Image

For a visually appealing touch, you can set a background image for the 'TabBar' using a 'Container' with a 'decoration':

Copy
AppBar(
  title: Text('Flutter TabBar Example'),
  bottom: Container(
    decoration: BoxDecoration(
      image: DecorationImage(
        image: AssetImage('assets/tab_bar_background.jpg'),
        fit: BoxFit.cover,
      ),
    ),
    child: TabBar(
      tabs: [...],
    ),
  ),
),

Custom Indicator

Create a custom tab indicator using the 'indicator' property of 'TabBar'. This allows you to design unique indicators that align with your app’s aesthetics:

Copy
TabBar(
  indicator: MyCustomIndicator(),
  tabs: [...],
),

Making Scrollable Tabs with TabBar

Horizontally Scrollable Tabs

When you have numerous tabs, you can enable horizontal scrolling by wrapping your 'TabBar' in a 'SingleChildScrollView':

Copy
SingleChildScrollView(
  scrollDirection: Axis.horizontal,
  child: TabBar(
    tabs: [...],
  ),
),

Vertically Scrollable Tabs

In scenarios where vertical space is limited, you can apply vertical scrolling to your 'TabBar' using a 'ListView' or 'CustomScrollView':

Copy
ListView(
  scrollDirection: Axis.vertical,
  children: [
    TabBar(
      tabs: [...],
    ),
    // Other content
  ],
),

Changing Tabs Programmatically

You can programmatically change the selected tab using the 'DefaultTabController' and its 'animateTo' method. This is particularly useful when you want to navigate to a specific tab based on user interactions:

Copy
DefaultTabController.of(context).animateTo(1); // Navigates to Tab 2

Listening for Tab Change Event

To listen for tab change events, you can use the 'TabController' and its 'addListener' method. This enables you to perform specific actions when users switch between tabs:

Copy
TabController _tabController;


void initState() {
  super.initState();
  _tabController = DefaultTabController.of(context);
  _tabController.addListener(_onTabChanged);
}

void _onTabChanged() {
  // Do something when tab changes
}

How to Implement TabBar Without AppBar

Should you require a standalone TabBar outside of an AppBar, you can place it within a 'Container' or 'Card' to create a distinctive visual separation:

Copy
Container(
  color: Colors.grey[200],
  child: TabBar(
    tabs: [...],
  ),
),

Preserving the State of Tabs

To maintain the state of tabs when switching between them, you can employ the 'AutomaticKeepAliveClientMixin' along with the 'wantKeepAlive' method. This ensures that the state of each tab is retained even when navigating back and forth:

Copy
class Tab1Content extends StatefulWidget {
  
  _Tab1ContentState createState() => _Tab1ContentState();
}

class _Tab1ContentState extends State<Tab1Content>
    with AutomaticKeepAliveClientMixin<Tab1Content> {
  
  bool get wantKeepAlive => true;

  
  Widget build(BuildContext context) {
    super.build(context); // Make sure to call super.build
    return Center(child: Text('Content for Tab 1'));
  }
}

Conclusion

In this guide, we’ve covered the step-by-step process of implementing and customizing TabBar and TabBarView in your Flutter app. From setting up the basic structure to handling customization, scrollable tabs, and maintaining tab state, you’re now equipped with the knowledge to create seamless and interactive tab-based navigation in your Flutter applications. As you continue your journey in Flutter development, remember that mastering TabBar and TabBarView will significantly enhance the user experience and contribute to the overall success of your apps in 2023 and beyond.

Related Blogs
Adjusting MinSdkVersion in Flutter for Android: 2 Simple Approaches [2023]

Adjusting MinSdkVersion in Flutter for Android: 2 Simple Approaches [2023]

Enhance your Flutter app's compatibility by tweaking the Android minSdkVersion. This comprehensive guide covers easy techniques for projects pre and post Flutter 2.8, guaranteeing optimal functionality.

ANDROIDFLUTTERFLUTTER DEVELOPMENTMIN SDK VERSION

July 20, 2023

Unlocking Flutter's Potential: Best Practices for Writing Clean Code

Unlocking Flutter's Potential: Best Practices for Writing Clean Code

Unlock Flutter's potential with clean code! Learn best practices for writing maintainable Dart code in Flutter. Explore examples and essential principles for code quality.

CLEAN CODECODE BEST PRACTICESCODE MAINTAINABILITYCODE ORGANIZATIONCODE READABILITY

June 02, 2023

All about SOLID Principles in Flutter: Examples and Tips

All about SOLID Principles in Flutter: Examples and Tips

Check out this guide on SOLID principles in Flutter by Mihir Pipermitwala, a software engineer from Surat. Learn with real-world examples!

DARTFLUTTERSOLID PRINCIPLES

April 11, 2023

Top 9 Local Databases for Flutter in 2023: A Comprehensive Comparison

Top 9 Local Databases for Flutter in 2023: A Comprehensive Comparison

Looking for the best local database for your Flutter app? Check out our comprehensive comparison of the top 9 local databases for Flutter in 2023.

CODINGFLUTTERFLUTTER LOCAL DATABASESLEARN TO CODENOSQL

April 06, 2023

Related Tutorials
Essential Git Skills: How to Delete Remote Branches

Essential Git Skills: How to Delete Remote Branches

Managing branches is a crucial part of working with Git, especially when it comes to keeping your repository clean and organized. In this guide, we'll walk you through how to delete both local and remote branches in Git.

BITBUCKETDELETE LOCAL BRANCHDELETE REMOTE BRANCHGITGIT BRANCH CLEANUP AUTOMATION

June 12, 2024

A Comprehensive Guide to Flutter Buttons: Choosing the Right One for Your App

A Comprehensive Guide to Flutter Buttons: Choosing the Right One for Your App

A quick guide for you to understand and choose which Button widget suits your needs

CUPERTINO BUTTONELEVATED BUTTONFLOATING ACTION BUTTONFLUTTERFLUTTER BUTTON

April 17, 2024

How to Show Automatic Internet Connection Offline Message in Flutter

How to Show Automatic Internet Connection Offline Message in Flutter

You have to use the 'Connectivity Flutter Package' to achieve this feature on your App. This package helps to know whether your device is online or offline.

CONNECTIVITY PLUSDEPENDENCIESFLUTTERFLUTTER DEVELOPMENTFLUTTER PACKAGES

April 09, 2024

Mastering TabBar and TabBarView Implementation in Flutter: A Comprehensive Guide for 2023

Mastering TabBar and TabBarView Implementation in Flutter: A Comprehensive Guide for 2023

Discover the art of implementing TabBar and TabBarView widgets in Flutter with our comprehensive guide for 2023. Learn step by step how to create captivating user interfaces, customize tab indicators, enable scrollable tabs, change tabs programmatically, and more. Elevate your Flutter app's navigation and user experience with expert insights and practical examples.

CODINGDEFAULT TAB CONTROLLERFLUTTERLEARN TO CODETAB CONTROLLER

July 26, 2023

Related Recommended Services
Visual Studio Code for the Web

Visual Studio Code for the Web

Build with Visual Studio Code, anywhere, anytime, in your browser.

IDEVISUAL STUDIOVISUAL STUDIO CODEWEB
Renovate | Automated Dependency Updates

Renovate | Automated Dependency Updates

Renovate Bot keeps source code dependencies up-to-date using automated Pull Requests.

AUTOMATED DEPENDENCY UPDATESBUNDLERCOMPOSERGITHUBGO MODULES
Best XML Formatter and XML Beautifier

Best XML Formatter and XML Beautifier

Online XML Formatter will format xml data, helps to validate, and works as XML Converter. Save and Share XML.

XMLXML BEAUTIFIERXML CONVERTERXML FORMATXML FORMATTER
Kubecost | Kubernetes cost monitoring and management

Kubecost | Kubernetes cost monitoring and management

Kubecost started in early 2019 as an open-source tool to give developers visibility into Kubernetes spend. We maintain a deep commitment to building and supporting dedicated solutions for the open source community.

CLOUDKUBECOSTKUBERNETESOPEN SOURCESELF HOSTED
Related Recommended Stories
How GitHub reduced testing time for iOS apps with new runner features

How GitHub reduced testing time for iOS apps with new runner features

Learn how GitHub used macOS and Apple Silicon runners for GitHub Actions to build, test, and deploy our iOS app faster.

IOSGITHUBTESTINGRUNNER
5 ways to transform your workflow using GitHub Copilot and MCP

5 ways to transform your workflow using GitHub Copilot and MCP

Learn how to streamline your development workflow with five different MCP use cases.

AGENT MODECODING AGENTCOPILOTFIGMAGITHUB
One weird trick for powerful Git aliases

One weird trick for powerful Git aliases

Advanced Git Aliases

ALIASALIAS TEMPLATEATLASSIANBITBUCKETGIT
Awesome Python

Awesome Python

An opinionated list of awesome Python frameworks, libraries, software and resources

AWESOMEAWESOME PYTHONCOLLECTIONSGITHUBPYTHON
Related Recommended Tools
Find out what websites are built with - Wappalyzer

Find out what websites are built with - Wappalyzer

Find out the technology stack of any website. Create lists of websites and contacts by the technologies they use.

ADD ONSANALYTICSAPP STOREAPPLEBOOKING
Sourcetree | Free Git GUI for Mac and Windows

Sourcetree | Free Git GUI for Mac and Windows

A Git GUI that offers a visual representation of your repositories. Sourcetree is a free Git client for Windows and Mac.

GITGITHUBGITLABATLASSIANBITBUCKET
Related Recommended Videos