Flutter Tabs Tutorial

flutter-tabbar-example

In this tutorial, we're going to implement Flutter Tabs using DefaultTabController widget. If you're new to flutter please start here: flutter tutorial

I am going to create three tabs such as Chats, Groups,   Settings with respective icons. Let's start by creating new project (or) you can choose your existing project. Since, we're going to create simple UI, we're not going to use statefull widget.

flutter create TabExample
cd TabExample
flutter run
flutter-tabs-example

Things to Remember:

Let's code (lib/main.dart)

Flutter TabBar Example code

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget{
  
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(home: DefaultTabController(
      length: 3,
      child: Scaffold(
        appBar: AppBar(
          title: Text("CODESUNDAR"),
          leading: Icon(Icons.menu),
          backgroundColor: Colors.teal[700],
          actions: <Widget>[
            IconButton(icon: Icon(Icons.search), onPressed: () => { }),
            IconButton(icon: Icon(Icons.more_vert), onPressed: () => { })
          ],
          bottom: TabBar(
            indicatorColor: Colors.yellow,
            tabs: <Widget>[
              Tab(text: "Chats", icon:  Icon(Icons.chat)),
              Tab(text: "Groups", icon: Icon(Icons.group)),
              Tab(text: "Settings", icon: Icon(Icons.settings))
            ],
          ),
        ),
        body: TabBarView(
          children: <Widget>[
            Center(child: Text("Chat Tab")),
            Center(child: Text("Group Tab")),
            Center(child: Text("Settings Tab")),
          ],
        ),
      ),
    )
    );
  }
}

Flutter Tabs Example Explanation

  • First we have created a MaterialApp widget with DefaultTabController as home property
  • In DefaultTabContoller Widget, we need to pass number of Tabs, and child. In our case, we passed 3 (Chats, Group, Settings).
  • Inside child, we created scaffold with AppBar.(If you're not aware of AppBar, please read: Flutter AppBar Example ), where AppBar bottom propery contains TabBar widget.
  • TabBar Widget has tabs children as Tab() which requires icon and text
  • After completing AppBar, now we need to pass TabBarView on MaterialApp body property.
  • Since, we created three Tabs, we need three child

If you're facing any issue, feel free to comment below.