tab_controller.dart 13.5 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
Hans Muller's avatar
Hans Muller committed
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
import 'dart:math' as math;

Hans Muller's avatar
Hans Muller committed
7 8 9 10
import 'package:flutter/widgets.dart';

import 'constants.dart';

11
// Examples can assume:
12
// late BuildContext context;
13

Hans Muller's avatar
Hans Muller committed
14 15 16
/// Coordinates tab selection between a [TabBar] and a [TabBarView].
///
/// The [index] property is the index of the selected tab and the [animation]
Aditya Sharma's avatar
Aditya Sharma committed
17
/// represents the current scroll positions of the tab bar and the tab bar view.
Hans Muller's avatar
Hans Muller committed
18 19
/// The selected tab's index can be changed with [animateTo].
///
20
/// A stateful widget that builds a [TabBar] or a [TabBarView] can create
21 22 23
/// a [TabController] and share it directly.
///
/// When the [TabBar] and [TabBarView] don't have a convenient stateful
24 25
/// ancestor, a [TabController] can be shared by providing a
/// [DefaultTabController] inherited widget.
Hans Muller's avatar
Hans Muller committed
26
///
27 28
/// {@animation 700 540 https://flutter.github.io/assets-for-api-docs/assets/material/tabs.mp4}
///
29
/// {@tool snippet}
30
///
31 32
/// This widget introduces a [Scaffold] with an [AppBar] and a [TabBar].
///
33
/// ```dart
34
/// class MyTabbedPage extends StatefulWidget {
35
///   const MyTabbedPage({ Key? key }) : super(key: key);
36
///   @override
37
///   State<MyTabbedPage> createState() => _MyTabbedPageState();
38 39 40
/// }
///
/// class _MyTabbedPageState extends State<MyTabbedPage> with SingleTickerProviderStateMixin {
41
///   static const List<Tab> myTabs = <Tab>[
42 43
///     Tab(text: 'LEFT'),
///     Tab(text: 'RIGHT'),
44 45
///   ];
///
46
///   late TabController _tabController;
47 48 49 50
///
///   @override
///   void initState() {
///     super.initState();
51
///     _tabController = TabController(vsync: this, length: myTabs.length);
52 53 54 55 56 57 58 59 60 61
///   }
///
///  @override
///  void dispose() {
///    _tabController.dispose();
///    super.dispose();
///  }
///
///   @override
///   Widget build(BuildContext context) {
62 63 64
///     return Scaffold(
///       appBar: AppBar(
///         bottom: TabBar(
65 66 67 68
///           controller: _tabController,
///           tabs: myTabs,
///         ),
///       ),
69
///       body: TabBarView(
70 71
///         controller: _tabController,
///         children: myTabs.map((Tab tab) {
72
///           final String label = tab.text!.toLowerCase();
73 74 75 76 77 78
///           return Center(
///             child: Text(
///               'This is the $label tab',
///               style: const TextStyle(fontSize: 36),
///             ),
///           );
79 80 81 82 83 84
///         }).toList(),
///       ),
///     );
///   }
/// }
/// ```
85
/// {@end-tool}
86
///
87
/// {@tool dartpad}
88 89 90
/// This example shows how to listen to page updates in [TabBar] and [TabBarView]
/// when using [DefaultTabController].
///
91
/// ** See code in examples/api/lib/material/tab_controller/tab_controller.1.dart **
92 93
/// {@end-tool}
///
Hans Muller's avatar
Hans Muller committed
94
class TabController extends ChangeNotifier {
95 96
  /// Creates an object that manages the state required by [TabBar] and a
  /// [TabBarView].
97
  ///
98
  /// The [length] must not be null or negative. Typically it's a value greater
99 100
  /// than one, i.e. typically there are two or more tabs. The [length] must
  /// match [TabBar.tabs]'s and [TabBarView.children]'s length.
101
  ///
102 103
  /// The `initialIndex` must be valid given [length] and must not be null. If
  /// [length] is zero, then `initialIndex` must be 0 (the default).
104
  TabController({ int initialIndex = 0, required this.length, required TickerProvider vsync })
105 106
    : assert(length != null && length >= 0),
      assert(initialIndex != null && initialIndex >= 0 && (length == 0 || initialIndex < length)),
107
      _index = initialIndex,
Hans Muller's avatar
Hans Muller committed
108
      _previousIndex = initialIndex,
109
      _animationController = AnimationController.unbounded(
Hans Muller's avatar
Hans Muller committed
110
        value: initialIndex.toDouble(),
111
        vsync: vsync,
112
      );
Hans Muller's avatar
Hans Muller committed
113

114 115 116
  // Private constructor used by `_copyWith`. This allows a new TabController to
  // be created without having to create a new animationController.
  TabController._({
117 118 119 120
    required int index,
    required int previousIndex,
    required AnimationController? animationController,
    required this.length,
121 122 123 124 125 126 127 128
  }) : _index = index,
       _previousIndex = previousIndex,
       _animationController = animationController;


  /// Creates a new [TabController] with `index`, `previousIndex`, and `length`
  /// if they are non-null.
  ///
129
  /// This method is used by [DefaultTabController].
130
  ///
131 132
  /// When [DefaultTabController.length] is updated, this method is called to
  /// create a new [TabController] without creating a new [AnimationController].
133 134 135 136 137
  TabController _copyWith({
    required int? index,
    required int? length,
    required int? previousIndex,
  }) {
138 139 140
    if (index != null) {
      _animationController!.value = index.toDouble();
    }
141 142 143 144 145 146 147 148
    return TabController._(
      index: index ?? _index,
      length: length ?? this.length,
      animationController: _animationController,
      previousIndex: previousIndex ?? _previousIndex,
    );
  }

Hans Muller's avatar
Hans Muller committed
149 150 151 152 153 154 155 156
  /// An animation whose value represents the current position of the [TabBar]'s
  /// selected tab indicator as well as the scrollOffsets of the [TabBar]
  /// and [TabBarView].
  ///
  /// The animation's value ranges from 0.0 to [length] - 1.0. After the
  /// selected tab is changed, the animation's value equals [index]. The
  /// animation's value can be [offset] by +/- 1.0 to reflect [TabBarView]
  /// drag scrolling.
157
  ///
158
  /// If this [TabController] was disposed, then return null.
159 160
  Animation<double>? get animation => _animationController?.view;
  AnimationController? _animationController;
Hans Muller's avatar
Hans Muller committed
161

162 163 164 165
  /// The total number of tabs.
  ///
  /// Typically greater than one. Must match [TabBar.tabs]'s and
  /// [TabBarView.children]'s length.
Hans Muller's avatar
Hans Muller committed
166 167
  final int length;

168
  void _changeIndex(int value, { Duration? duration, Curve? curve }) {
Hans Muller's avatar
Hans Muller committed
169
    assert(value != null);
170
    assert(value >= 0 && (value < length || length == 0));
171
    assert(duration != null || curve == null);
Hans Muller's avatar
Hans Muller committed
172
    assert(_indexIsChangingCount >= 0);
173
    if (value == _index || length < 2)
Hans Muller's avatar
Hans Muller committed
174 175 176 177 178
      return;
    _previousIndex = index;
    _index = value;
    if (duration != null) {
      _indexIsChangingCount += 1;
179
      notifyListeners(); // Because the value of indexIsChanging may have changed.
180 181
      _animationController!
        .animateTo(_index.toDouble(), duration: duration, curve: curve!)
182
        .whenCompleteOrCancel(() {
183 184 185 186
          if (_animationController != null) { // don't notify if we've been disposed
            _indexIsChangingCount -= 1;
            notifyListeners();
          }
187
        });
Hans Muller's avatar
Hans Muller committed
188 189
    } else {
      _indexIsChangingCount += 1;
190
      _animationController!.value = _index.toDouble();
Hans Muller's avatar
Hans Muller committed
191 192 193 194 195
      _indexIsChangingCount -= 1;
      notifyListeners();
    }
  }

196 197 198 199
  /// The index of the currently selected tab.
  ///
  /// Changing the index also updates [previousIndex], sets the [animation]'s
  /// value to index, resets [indexIsChanging] to false, and notifies listeners.
Hans Muller's avatar
Hans Muller committed
200 201
  ///
  /// To change the currently selected tab and play the [animation] use [animateTo].
202 203 204
  ///
  /// The value of [index] must be valid given [length]. If [length] is zero,
  /// then [index] will also be zero.
Hans Muller's avatar
Hans Muller committed
205 206 207 208 209 210
  int get index => _index;
  int _index;
  set index(int value) {
    _changeIndex(value);
  }

211 212 213
  /// The index of the previously selected tab.
  ///
  /// Initially the same as [index].
Hans Muller's avatar
Hans Muller committed
214 215 216
  int get previousIndex => _previousIndex;
  int _previousIndex;

217 218 219 220 221 222
  /// True while we're animating from [previousIndex] to [index] as a
  /// consequence of calling [animateTo].
  ///
  /// This value is true during the [animateTo] animation that's triggered when
  /// the user taps a [TabBar] tab. It is false when [offset] is changing as a
  /// consequence of the user dragging (and "flinging") the [TabBarView].
Hans Muller's avatar
Hans Muller committed
223 224 225 226 227 228 229 230
  bool get indexIsChanging => _indexIsChangingCount != 0;
  int _indexIsChangingCount = 0;

  /// Immediately sets [index] and [previousIndex] and then plays the
  /// [animation] from its current value to [index].
  ///
  /// While the animation is running [indexIsChanging] is true. When the
  /// animation completes [offset] will be 0.0.
231
  void animateTo(int value, { Duration duration = kTabScrollDuration, Curve curve = Curves.ease }) {
Hans Muller's avatar
Hans Muller committed
232 233 234
    _changeIndex(value, duration: duration, curve: curve);
  }

235 236 237
  /// The difference between the [animation]'s value and [index].
  ///
  /// The offset value must be between -1.0 and 1.0.
Hans Muller's avatar
Hans Muller committed
238 239 240 241 242
  ///
  /// This property is typically set by the [TabBarView] when the user
  /// drags left or right. A value between -1.0 and 0.0 implies that the
  /// TabBarView has been dragged to the left. Similarly a value between
  /// 0.0 and 1.0 implies that the TabBarView has been dragged to the right.
243
  double get offset => _animationController!.value - _index.toDouble();
244 245 246
  set offset(double value) {
    assert(value != null);
    assert(value >= -1.0 && value <= 1.0);
Hans Muller's avatar
Hans Muller committed
247
    assert(!indexIsChanging);
248
    if (value == offset)
Hans Muller's avatar
Hans Muller committed
249
      return;
250
    _animationController!.value = value + _index.toDouble();
Hans Muller's avatar
Hans Muller committed
251 252 253 254
  }

  @override
  void dispose() {
255
    _animationController?.dispose();
256
    _animationController = null;
Hans Muller's avatar
Hans Muller committed
257 258 259 260 261
    super.dispose();
  }
}

class _TabControllerScope extends InheritedWidget {
262
  const _TabControllerScope({
263 264 265 266
    Key? key,
    required this.controller,
    required this.enabled,
    required Widget child,
Hans Muller's avatar
Hans Muller committed
267 268 269 270 271 272 273 274 275 276 277
  }) : super(key: key, child: child);

  final TabController controller;
  final bool enabled;

  @override
  bool updateShouldNotify(_TabControllerScope old) {
    return enabled != old.enabled || controller != old.controller;
  }
}

278 279
/// The [TabController] for descendant widgets that don't specify one
/// explicitly.
280
///
281 282
/// {@youtube 560 315 https://www.youtube.com/watch?v=POtoEH-5l40}
///
283 284 285 286 287
/// [DefaultTabController] is an inherited widget that is used to share a
/// [TabController] with a [TabBar] or a [TabBarView]. It's used when sharing an
/// explicitly created [TabController] isn't convenient because the tab bar
/// widgets are created by a stateless parent widget or by different parent
/// widgets.
288
///
289 290
/// {@animation 700 540 https://flutter.github.io/assets-for-api-docs/assets/material/tabs.mp4}
///
291 292 293
/// ```dart
/// class MyDemo extends StatelessWidget {
///   final List<Tab> myTabs = <Tab>[
294 295
///     Tab(text: 'LEFT'),
///     Tab(text: 'RIGHT'),
296 297 298 299
///   ];
///
///   @override
///   Widget build(BuildContext context) {
300
///     return DefaultTabController(
301
///       length: myTabs.length,
302 303 304
///       child: Scaffold(
///         appBar: AppBar(
///           bottom: TabBar(
305 306 307
///             tabs: myTabs,
///           ),
///         ),
308
///         body: TabBarView(
309
///           children: myTabs.map((Tab tab) {
310 311 312 313 314 315 316
///             final String label = tab.text.toLowerCase();
///             return Center(
///               child: Text(
///                 'This is the $label tab',
///                 style: const TextStyle(fontSize: 36),
///               ),
///             );
317 318 319 320 321 322 323
///           }).toList(),
///         ),
///       ),
///     );
///   }
/// }
/// ```
Hans Muller's avatar
Hans Muller committed
324
class DefaultTabController extends StatefulWidget {
325 326
  /// Creates a default tab controller for the given [child] widget.
  ///
327 328
  /// The [length] argument is typically greater than one. The [length] must
  /// match [TabBar.tabs]'s and [TabBarView.children]'s length.
329 330
  ///
  /// The [initialIndex] argument must not be null.
331
  const DefaultTabController({
332 333
    Key? key,
    required this.length,
334
    this.initialIndex = 0,
335
    required this.child,
336
  }) : assert(initialIndex != null),
337
       assert(length >= 0),
338
       assert(length == 0 || (initialIndex >= 0 && initialIndex < length)),
339
       super(key: key);
Hans Muller's avatar
Hans Muller committed
340

341 342 343 344
  /// The total number of tabs.
  ///
  /// Typically greater than one. Must match [TabBar.tabs]'s and
  /// [TabBarView.children]'s length.
Hans Muller's avatar
Hans Muller committed
345 346 347
  final int length;

  /// The initial index of the selected tab.
348 349
  ///
  /// Defaults to zero.
Hans Muller's avatar
Hans Muller committed
350 351
  final int initialIndex;

352 353 354 355
  /// The widget below this widget in the tree.
  ///
  /// Typically a [Scaffold] whose [AppBar] includes a [TabBar].
  ///
356
  /// {@macro flutter.widgets.ProxyWidget.child}
Hans Muller's avatar
Hans Muller committed
357 358 359 360
  final Widget child;

  /// The closest instance of this class that encloses the given context.
  ///
361
  /// {@tool snippet}
362
  /// Typical usage is as follows:
Hans Muller's avatar
Hans Muller committed
363 364
  ///
  /// ```dart
365
  /// TabController controller = DefaultTabController.of(context)!;
Hans Muller's avatar
Hans Muller committed
366
  /// ```
367
  /// {@end-tool}
368 369
  static TabController? of(BuildContext context) {
    final _TabControllerScope? scope = context.dependOnInheritedWidgetOfExactType<_TabControllerScope>();
Hans Muller's avatar
Hans Muller committed
370 371 372 373
    return scope?.controller;
  }

  @override
374
  State<DefaultTabController> createState() => _DefaultTabControllerState();
Hans Muller's avatar
Hans Muller committed
375 376 377
}

class _DefaultTabControllerState extends State<DefaultTabController> with SingleTickerProviderStateMixin {
378
  late TabController _controller;
Hans Muller's avatar
Hans Muller committed
379 380 381 382

  @override
  void initState() {
    super.initState();
383
    _controller = TabController(
Hans Muller's avatar
Hans Muller committed
384
      vsync: this,
385 386
      length: widget.length,
      initialIndex: widget.initialIndex,
Hans Muller's avatar
Hans Muller committed
387 388 389 390 391 392 393 394 395 396 397
    );
  }

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

  @override
  Widget build(BuildContext context) {
398
    return _TabControllerScope(
Hans Muller's avatar
Hans Muller committed
399 400
      controller: _controller,
      enabled: TickerMode.of(context),
401
      child: widget.child,
Hans Muller's avatar
Hans Muller committed
402 403
    );
  }
404 405 406 407 408 409 410

  @override
  void didUpdateWidget(DefaultTabController oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.length != widget.length) {
      // If the length is shortened while the last tab is selected, we should
      // automatically update the index of the controller to be the new last tab.
411
      int? newIndex;
412 413 414 415 416 417 418 419 420 421 422 423
      int previousIndex = _controller.previousIndex;
      if (_controller.index >= widget.length) {
        newIndex = math.max(0, widget.length - 1);
        previousIndex = _controller.index;
      }
      _controller = _controller._copyWith(
        length: widget.length,
        index: newIndex,
        previousIndex: previousIndex,
      );
    }
  }
Hans Muller's avatar
Hans Muller committed
424
}