How to add tabs in flutter with example

In Flutter, you can add tabs to your app using the TabBar and TabBarView widgets.

Here’s an example code snippet that demonstrates how to add tabs in Flutter:

import 'package:flutter/material.dart';

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


class MyTabsScreen extends StatefulWidget {
  @override
  _MyTabsScreenState createState() => _MyTabsScreenState();
}

class _MyTabsScreenState extends State<MyTabsScreen> with SingleTickerProviderStateMixin {
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('flutterfever.com'),
          bottom: TabBar(
            controller: _tabController,
            tabs: [
              Tab(text: 'Tab 1'),
              Tab(text: 'Tab 2'),
            ],
          ),
        ),
        body: TabBarView(
          controller: _tabController,
          children: [
            Center(child: Text('Tab 1 flutterfever.com')),
            Center(child: Text('Tab 2 flutterfever.com')),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }
}

output:

In the code above, we created a TabController instance _tabController and passed it to both the TabBar and TabBarView widgets. We also implemented the SingleTickerProviderStateMixin mixin to provide the necessary animation ticker for the TabController.

The TabBar widget is added to the AppBar as the bottom property. We passed the _tabController instance to the controller property and defined two tabs using the Tab widget.

The TabBarView widget is added as the body property of the Scaffold. We also passed the _tabController instance to the controller property and defined the contents of each tab using the children property.

When the user taps on a tab, the _tabController instance will handle the tab switching and animate the transition between the tabs.

Finally, we dispose of the _tabController instance in the dispose() method to prevent any memory leaks.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More