tab_controller.1.dart 1.76 KB
Newer Older
1 2 3 4 5 6
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/material.dart';

7
/// Flutter code sample for [TabController].
8

9
void main() => runApp(const TabControllerExampleApp());
10

11 12
class TabControllerExampleApp extends StatelessWidget {
  const TabControllerExampleApp({super.key});
13 14 15 16

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
17
      home: TabControllerExample(),
18 19 20 21 22 23 24 25 26 27
    );
  }
}

const List<Tab> tabs = <Tab>[
  Tab(text: 'Zeroth'),
  Tab(text: 'First'),
  Tab(text: 'Second'),
];

28 29
class TabControllerExample extends StatelessWidget {
  const TabControllerExample({super.key});
30 31 32 33 34 35 36 37

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: tabs.length,
      // The Builder widget is used to have a different BuildContext to access
      // closest DefaultTabController.
      child: Builder(builder: (BuildContext context) {
38
        final TabController tabController = DefaultTabController.of(context);
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
        tabController.addListener(() {
          if (!tabController.indexIsChanging) {
            // Your code goes here.
            // To get index of current tab use tabController.index
          }
        });
        return Scaffold(
          appBar: AppBar(
            bottom: const TabBar(
              tabs: tabs,
            ),
          ),
          body: TabBarView(
            children: tabs.map((Tab tab) {
              return Center(
                child: Text(
                  '${tab.text!} Tab',
56
                  style: Theme.of(context).textTheme.headlineSmall,
57 58 59 60 61 62 63 64 65
                ),
              );
            }).toList(),
          ),
        );
      }),
    );
  }
}