How to Add Tabs in Flutter

In this example, we are going to show you how to add a Tab Bar widget using TabBar and TabBarView in Flutter. Tabs are very important components of any kind of user interface for sectioned layout. See the example below:

First, wrap your widget tree with DefaultTabController() before using TabBar and TabBarView.

DefaultTabController( 
  initialIndex: 1,  //optional, starts from 0, select the tab by default
  length:3,
  child:Scaffold(
     
  )
)

Now, Place the TabBar() where you want to display the Tabs in your app. Here, we are showing below the AppBar.

AppBar(
  bottom: TabBar(
    tabs: [
        Tab(text: "Home",),
        Tab(text: "About Us",),
        Tab(text: "Contact Us",)
    ]
  )
)

Now, place the TabBarView() where you want to display the contents.

TabBarView(
    children: [
        Container( //for first tab
            height: 400,
            color: Colors.red,
        ),
        Container( //for second tab
            height: 400,
            color: Colors.green,
        ),
        Container( //for third tab
          height: 400,
            color: Colors.blue,
        )
    ]
)

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget{
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> { 

  @override
  Widget build(BuildContext context) { 
    return  DefaultTabController( 
      initialIndex: 1,  //optional, starts from 0, select the tab by default
      length:3,
      child:Scaffold(
          appBar: AppBar(
            title: Text("Tab in Flutter"),
            backgroundColor: Colors.lightGreen,
            bottom: TabBar(
                      tabs: [
                          Tab(text: "Home",),
                          Tab(text: "About Us",),
                          Tab(text: "Contact Us",)
                      ]
                    ),
          ),
          
          body: TabBarView(
              children: [
                  Container( //for first tab
                      height: 400,
                      color: Colors.red,
                  ),
                  Container( //for second tab
                      height: 400,
                      color: Colors.green,
                  ),
                  Container( //for third tab
                    height: 400,
                      color: Colors.blue,
                  )
              ]
          )
       )
    );
  }
}

In this way, you can add Tabs in the Flutter app.

No any Comments on this Article


Please Wait...