Flutter - tab layout/view

Flutter - tab layout/view

·

2 min read

In Flutter, you can create a tab layout using the TabBar and TabBarView widgets. The TabBar widget displays a horizontal row of tabs, and the TabBarView widget displays the content corresponding to each tab.

Here's an example of how to create a simple tab layout in Flutter:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Tab Bar Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const TabBarPage(),
    );
  }
}

class TabBarPage extends StatelessWidget {
  const TabBarPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 3, // Number of tabs
      child: Scaffold(
        appBar: AppBar(
          title: const Text('Tab Bar Example'),
          bottom: const TabBar(
            tabs: [
              Tab(text: 'Tab 1'),
              Tab(text: 'Tab 2'),
              Tab(text: 'Tab 3'),
            ],
          ),
        ),
        body: const TabBarView(
          children: [
            Center(child: Text('Tab 1 content')),
            Center(child: Text('Tab 2 content')),
            Center(child: Text('Tab 3 content')),
          ],
        ),
      ),
    );
  }
}

In this example, we create a MyTabLayout widget, which is a stateful widget that holds the TabController responsible for managing the tab selection. In the initState method, we initialize the TabController with a length of 3, indicating that we have 3 tabs. We also set vsync: this to synchronize the animation of the TabBar with the current TickerProvider.

Inside the build method, we use the Scaffold widget as the root widget, which provides the basic layout structure. The AppBar widget is placed at the top and contains the title and the TabBar widget as its bottom property. We pass the TabController to the TabBar using the controller property and define the tabs with the tabs property.

Below the AppBar, we use the TabBarView widget to display the content for each tab. We pass the same TabController to the TabBarView as well using the controller property. Inside the children property of TabBarView, we define the content for each tab using different Center widgets with corresponding text.

This is a basic example of how to create a tab layout in Flutter. You can customize the appearance and behavior of the tabs and their content further according to your needs.