How to Create Tabs in Flutter

I have already shown how to create bottom tabs as well as how to create navigation drawer in Flutter in the previous blog posts. Here, let’s check how to create normal material tabs in Flutter.

In this Flutter tabs example, we will have three tabs named Tab 1, Tab 2 and Tab 3 at the top. At first, create a file named tab1.dart as it shows the content of the Tab1.

import 'package:flutter/material.dart';

class Tab1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return TabMain();
  }
}

/// This is the stateless widget that the main application instantiates.
class TabMain extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(child: Text('This is Tab One'),)
    );
  }
}

Similarly create tab2.dart and tab3.dart.

Now let’s come to the main code.

import 'package:flutter/material.dart';
import 'package:flutter_tabs_example/tab1.dart';
import 'package:flutter_tabs_example/tab2.dart';
import 'package:flutter_tabs_example/tab3.dart';

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

class FlutterTabsExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 3,
        child: Scaffold(
          
          appBar: AppBar(
            title: Center(child:Text('Flutter Tabs Example')),
            bottom: TabBar(
              tabs: [
                Tab(icon: Icon(Icons.local_movies),text: 'Tab 1', ),
                Tab(icon: Icon(Icons.face), text: 'Tab 2',),
                Tab(icon: Icon(Icons.favorite), text: 'Tab 3',),
              ],
            ),
            // title: Text('Tabs Demo'),
          ),
          body: TabBarView(
            children: [
              Tab1(),
              Tab2(),
              Tab3()
            ],
          ),
        ),
      ),
    );
  }
}

Let’s break down the things. First of all, we must have a TabController and here we used DefaultTabController which specified the number of tabs. Next we created tabs under the AppBar using TabBar and Tab. Here, we have both icon and text in a tab. After that we defined content of each tab using TabBarView widget.

Following is the output of Flutter Material Tabs example.

Flutter Tabs Tutorial

I hope you liked this Flutter tutorial!

Similar Posts

One Comment

Leave a Reply