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

import 'package:flutter/widgets.dart';
import 'bottom_tab_bar.dart';
7
import 'colors.dart';
xster's avatar
xster committed
8
import 'theme.dart';
9

10 11 12 13 14 15 16
/// Coordinates tab selection between a [CupertinoTabBar] and a [CupertinoTabScaffold].
///
/// The [index] property is the index of the selected tab. Changing its value
/// updates the actively displayed tab of the [CupertinoTabScaffold] the
/// [CupertinoTabController] controls, as well as the currently selected tab item of
/// its [CupertinoTabBar].
///
17
/// {@tool snippet}
18 19 20 21 22
///
/// [CupertinoTabController] can be used to switch tabs:
///
/// ```dart
/// class MyCupertinoTabScaffoldPage extends StatefulWidget {
23 24
///   const MyCupertinoTabScaffoldPage({Key? key}) : super(key: key);
///
25
///   @override
26
///   State<MyCupertinoTabScaffoldPage> createState() => _CupertinoTabScaffoldPageState();
27 28 29 30 31 32 33 34 35
/// }
///
/// class _CupertinoTabScaffoldPageState extends State<MyCupertinoTabScaffoldPage> {
///   final CupertinoTabController _controller = CupertinoTabController();
///
///   @override
///   Widget build(BuildContext context) {
///     return CupertinoTabScaffold(
///       tabBar: CupertinoTabBar(
36
///         items: const <BottomNavigationBarItem> [
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
///           // ...
///         ],
///       ),
///       controller: _controller,
///       tabBuilder: (BuildContext context, int index) {
///         return Center(
///           child: CupertinoButton(
///             child: const Text('Go to first tab'),
///             onPressed: () => _controller.index = 0,
///           )
///         );
///       }
///     );
///   }
///
///   @override
///   void dispose() {
///     _controller.dispose();
///     super.dispose();
///   }
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
63 64
///  * [CupertinoTabScaffold], a tabbed application root layout that can be
///    controlled by a [CupertinoTabController].
65 66
///  * [RestorableCupertinoTabController], which is a restorable version
///    of this controller.
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
class CupertinoTabController extends ChangeNotifier {
  /// Creates a [CupertinoTabController] to control the tab index of [CupertinoTabScaffold]
  /// and [CupertinoTabBar].
  ///
  /// The [initialIndex] must not be null and defaults to 0. The value must be
  /// greater than or equal to 0, and less than the total number of tabs.
  CupertinoTabController({ int initialIndex = 0 })
    : _index = initialIndex,
      assert(initialIndex != null),
      assert(initialIndex >= 0);

  bool _isDisposed = false;

  /// The index of the currently selected tab.
  ///
  /// Changing the value of [index] updates the actively displayed tab of the
  /// [CupertinoTabScaffold] controlled by this [CupertinoTabController], as well
  /// as the currently selected tab item of its [CupertinoTabScaffold.tabBar].
  ///
  /// The value must be greater than or equal to 0, and less than the total
  /// number of tabs.
  int get index => _index;
  int _index;
  set index(int value) {
    assert(value != null);
    assert(value >= 0);
    if (_index == value) {
      return;
    }
    _index = value;
    notifyListeners();
  }

  @mustCallSuper
  @override
  void dispose() {
    super.dispose();
    _isDisposed = true;
  }
}

108 109 110 111 112 113 114 115 116
/// Implements a tabbed iOS application's root layout and behavior structure.
///
/// The scaffold lays out the tab bar at the bottom and the content between or
/// behind the tab bar.
///
/// A [tabBar] and a [tabBuilder] are required. The [CupertinoTabScaffold]
/// will automatically listen to the provided [CupertinoTabBar]'s tap callbacks
/// to change the active tab.
///
117 118 119 120 121 122
/// A [controller] can be used to provide an initially selected tab index and manage
/// subsequent tab changes. If a controller is not specified, the scaffold will
/// create its own [CupertinoTabController] and manage it internally. Otherwise
/// it's up to the owner of [controller] to call `dispose` on it after finish
/// using it.
///
123
/// Tabs' contents are built with the provided [tabBuilder] at the active
124
/// tab index. The [tabBuilder] must be able to build the same number of
Dan Field's avatar
Dan Field committed
125
/// pages as there are [tabBar] items. Inactive tabs will be moved [Offstage]
126
/// and their animations disabled.
127
///
128 129 130 131
/// Adding/removing tabs, or changing the order of tabs is supported but not
/// recommended. Doing so is against the iOS human interface guidelines, and
/// [CupertinoTabScaffold] may lose some tabs' state in the process.
///
132 133 134 135 136 137 138 139
/// Use [CupertinoTabView] as the root widget of each tab to support tabs with
/// parallel navigation state and history. Since each [CupertinoTabView] contains
/// a [Navigator], rebuilding the [CupertinoTabView] with a different
/// [WidgetBuilder] instance in [CupertinoTabView.builder] will not recreate
/// the [CupertinoTabView]'s navigation stack or update its UI. To update the
/// contents of the [CupertinoTabView] after it's built, trigger a rebuild
/// (via [State.setState], for instance) from its descendant rather than from
/// its ancestor.
140
///
141
/// {@tool snippet}
142 143 144 145
///
/// A sample code implementing a typical iOS information architecture with tabs.
///
/// ```dart
146 147
/// CupertinoTabScaffold(
///   tabBar: CupertinoTabBar(
148
///     items: const <BottomNavigationBarItem> [
149 150 151 152
///       // ...
///     ],
///   ),
///   tabBuilder: (BuildContext context, int index) {
153
///     return CupertinoTabView(
154
///       builder: (BuildContext context) {
155 156 157
///         return CupertinoPageScaffold(
///           navigationBar: CupertinoNavigationBar(
///             middle: Text('Page 1 of tab $index'),
158
///           ),
159 160
///           child: Center(
///             child: CupertinoButton(
161 162 163
///               child: const Text('Next page'),
///               onPressed: () {
///                 Navigator.of(context).push(
164
///                   CupertinoPageRoute<void>(
165
///                     builder: (BuildContext context) {
166 167 168
///                       return CupertinoPageScaffold(
///                         navigationBar: CupertinoNavigationBar(
///                           middle: Text('Page 2 of tab $index'),
169
///                         ),
170 171
///                         child: Center(
///                           child: CupertinoButton(
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
///                             child: const Text('Back'),
///                             onPressed: () { Navigator.of(context).pop(); },
///                           ),
///                         ),
///                       );
///                     },
///                   ),
///                 );
///               },
///             ),
///           ),
///         );
///       },
///     );
///   },
/// )
/// ```
189
/// {@end-tool}
190
///
191 192 193 194 195
/// To push a route above all tabs instead of inside the currently selected one
/// (such as when showing a dialog on top of this scaffold), use
/// `Navigator.of(rootNavigator: true)` from inside the [BuildContext] of a
/// [CupertinoTabView].
///
196 197
/// See also:
///
198
///  * [CupertinoTabBar], the bottom tab bar inserted in the scaffold.
199
///  * [CupertinoTabController], the selection state of this widget.
200
///  * [CupertinoTabView], the typical root content of each tab that holds its own
201
///    [Navigator] stack.
202 203
///  * [CupertinoPageRoute], a route hosting modal pages with iOS style transitions.
///  * [CupertinoPageScaffold], typical contents of an iOS modal page implementing
204
///    layout with a navigation bar on top.
205
///  * [iOS human interface guidelines](https://developer.apple.com/design/human-interface-guidelines/ios/bars/tab-bars/).
206
class CupertinoTabScaffold extends StatefulWidget {
207 208
  /// Creates a layout for applications with a tab bar at the bottom.
  ///
209
  /// The [tabBar] and [tabBuilder] arguments must not be null.
210
  CupertinoTabScaffold({
211 212 213
    Key? key,
    required this.tabBar,
    required this.tabBuilder,
214
    this.controller,
215 216
    this.backgroundColor,
    this.resizeToAvoidBottomInset = true,
217
    this.restorationId,
218 219
  }) : assert(tabBar != null),
       assert(tabBuilder != null),
220 221 222
       assert(
         controller == null || controller.index < tabBar.items.length,
         "The CupertinoTabController's current index ${controller.index} is "
223
         'out of bounds for the tab bar with ${tabBar.items.length} tabs',
224
       ),
225 226 227 228 229 230
       super(key: key);

  /// The [tabBar] is a [CupertinoTabBar] drawn at the bottom of the screen
  /// that lets the user switch between different tabs in the main content area
  /// when present.
  ///
231 232 233 234 235 236
  /// The [CupertinoTabBar.currentIndex] is only used to initialize a
  /// [CupertinoTabController] when no [controller] is provided. Subsequently
  /// providing a different [CupertinoTabBar.currentIndex] does not affect the
  /// scaffold or the tab bar's active tab index. To programmatically change
  /// the active tab index, use a [CupertinoTabController].
  ///
237 238
  /// If [CupertinoTabBar.onTap] is provided, it will still be called.
  /// [CupertinoTabScaffold] automatically also listen to the
239
  /// [CupertinoTabBar]'s `onTap` to change the [controller]'s `index`
240 241 242 243 244
  /// and change the actively displayed tab in [CupertinoTabScaffold]'s own
  /// main content area.
  ///
  /// If translucent, the main content may slide behind it.
  /// Otherwise, the main content's bottom margin will be offset by its height.
245
  ///
246 247 248 249 250 251 252 253
  /// By default `tabBar` has its text scale factor set to 1.0 and does not
  /// respond to text scale factor changes from the operating system, to match
  /// the native iOS behavior. To override this behavior, wrap each of the `tabBar`'s
  /// items inside a [MediaQuery] with the desired [MediaQueryData.textScaleFactor]
  /// value. The text scale factor value from the operating system can be retrieved
  /// int many ways, such as querying [MediaQuery.textScaleFactorOf] against
  /// [CupertinoApp]'s [BuildContext].
  ///
254
  /// Must not be null.
255 256
  final CupertinoTabBar tabBar;

257 258 259 260 261 262
  /// Controls the currently selected tab index of the [tabBar], as well as the
  /// active tab index of the [tabBuilder]. Providing a different [controller]
  /// will also update the scaffold's current active index to the new controller's
  /// index value.
  ///
  /// Defaults to null.
263
  final CupertinoTabController? controller;
264

265 266
  /// An [IndexedWidgetBuilder] that's called when tabs become active.
  ///
267 268 269
  /// The widgets built by [IndexedWidgetBuilder] are typically a
  /// [CupertinoTabView] in order to achieve the parallel hierarchical
  /// information architecture seen on iOS apps with tab bars.
270
  ///
271 272
  /// When the tab becomes inactive, its content is cached in the widget tree
  /// [Offstage] and its animations disabled.
273
  ///
274 275 276 277
  /// Content can slide under the [tabBar] when they're translucent.
  /// In that case, the child's [BuildContext]'s [MediaQuery] will have a
  /// bottom padding indicating the area of obstructing overlap from the
  /// [tabBar].
278 279
  ///
  /// Must not be null.
280 281
  final IndexedWidgetBuilder tabBuilder;

282 283 284
  /// The color of the widget that underlies the entire scaffold.
  ///
  /// By default uses [CupertinoTheme]'s `scaffoldBackgroundColor` when null.
285
  final Color? backgroundColor;
286

Dan Field's avatar
Dan Field committed
287
  /// Whether the body should size itself to avoid the window's bottom inset.
288 289 290 291 292 293 294 295
  ///
  /// For example, if there is an onscreen keyboard displayed above the
  /// scaffold, the body can be resized to avoid overlapping the keyboard, which
  /// prevents widgets inside the body from being obscured by the keyboard.
  ///
  /// Defaults to true and cannot be null.
  final bool resizeToAvoidBottomInset;

296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
  /// Restoration ID to save and restore the state of the [CupertinoTabScaffold].
  ///
  /// This property only has an effect when no [controller] has been provided:
  /// If it is non-null (and no [controller] has been provided), the scaffold
  /// will persist and restore the currently selected tab index. If a
  /// [controller] has been provided, it is the responsibility of the owner of
  /// that controller to persist and restore it, e.g. by using a
  /// [RestorableCupertinoTabController].
  ///
  /// The state of this widget is persisted in a [RestorationBucket] claimed
  /// from the surrounding [RestorationScope] using the provided restoration ID.
  ///
  /// See also:
  ///
  ///  * [RestorationManager], which explains how state restoration works in
  ///    Flutter.
  final String? restorationId;

314
  @override
315
  State<CupertinoTabScaffold> createState() => _CupertinoTabScaffoldState();
316 317
}

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
class _CupertinoTabScaffoldState extends State<CupertinoTabScaffold> with RestorationMixin {
  RestorableCupertinoTabController? _internalController;
  CupertinoTabController get _controller =>  widget.controller ?? _internalController!.value;

  @override
  String? get restorationId => widget.restorationId;

  @override
  void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
    _restoreInternalController();
  }

  void _restoreInternalController() {
    if (_internalController != null) {
      registerForRestoration(_internalController!, 'controller');
      _internalController!.value.addListener(_onCurrentIndexChange);
    }
  }
336 337 338 339

  @override
  void initState() {
    super.initState();
340 341 342
    _updateTabController();
  }

343 344 345 346 347 348 349
  void _updateTabController([CupertinoTabController? oldWidgetController]) {
    if (widget.controller == null && _internalController == null) {
      // No widget-provided controller: create an internal controller.
      _internalController = RestorableCupertinoTabController(initialIndex: widget.tabBar.currentIndex);
      if (!restorePending) {
        _restoreInternalController(); // Also adds the listener to the controller.
      }
350
    }
351 352 353 354 355 356 357 358 359 360 361 362
    if (widget.controller != null && _internalController != null) {
      // Use the widget-provided controller.
      unregisterFromRestoration(_internalController!);
      _internalController!.dispose();
      _internalController = null;
    }
    if (oldWidgetController != widget.controller) {
      // The widget-provided controller has changed: move listeners.
      if (oldWidgetController?._isDisposed == false) {
        oldWidgetController!.removeListener(_onCurrentIndexChange);
      }
      widget.controller?.addListener(_onCurrentIndexChange);
363 364 365 366 367
    }
  }

  void _onCurrentIndexChange() {
    assert(
368 369
      _controller.index >= 0 && _controller.index < widget.tabBar.items.length,
      "The $runtimeType's current index ${_controller.index} is "
370
      'out of bounds for the tab bar with ${widget.tabBar.items.length} tabs',
371 372 373 374 375
    );

    // The value of `_controller.index` has already been updated at this point.
    // Calling `setState` to rebuild using `_controller.index`.
    setState(() {});
376 377 378 379 380
  }

  @override
  void didUpdateWidget(CupertinoTabScaffold oldWidget) {
    super.didUpdateWidget(oldWidget);
381
    if (widget.controller != oldWidget.controller) {
382 383
      _updateTabController(oldWidget.controller);
    } else if (_controller.index >= widget.tabBar.items.length) {
384 385
      // If a new [tabBar] with less than (_controller.index + 1) items is provided,
      // clamp the current index.
386
      _controller.index = widget.tabBar.items.length - 1;
387 388
    }
  }
389 390 391

  @override
  Widget build(BuildContext context) {
392 393
    final MediaQueryData existingMediaQuery = MediaQuery.of(context);
    MediaQueryData newMediaQuery = MediaQuery.of(context);
394

395
    Widget content = _TabSwitchingView(
396
      currentTabIndex: _controller.index,
397
      tabCount: widget.tabBar.items.length,
398
      tabBuilder: widget.tabBuilder,
399
    );
400
    EdgeInsets contentPadding = EdgeInsets.zero;
401

402 403 404
    if (widget.resizeToAvoidBottomInset) {
      // Remove the view inset and add it back as a padding in the inner content.
      newMediaQuery = newMediaQuery.removeViewInsets(removeBottom: true);
405
      contentPadding = EdgeInsets.only(bottom: existingMediaQuery.viewInsets.bottom);
406
    }
407

408 409 410 411 412 413
    if (widget.tabBar != null &&
        // Only pad the content with the height of the tab bar if the tab
        // isn't already entirely obstructed by a keyboard or other view insets.
        // Don't double pad.
        (!widget.resizeToAvoidBottomInset ||
            widget.tabBar.preferredSize.height > existingMediaQuery.viewInsets.bottom)) {
414 415
      // TODO(xster): Use real size after partial layout instead of preferred size.
      // https://github.com/flutter/flutter/issues/12912
xster's avatar
xster committed
416 417
      final double bottomPadding =
          widget.tabBar.preferredSize.height + existingMediaQuery.padding.bottom;
418 419 420 421

      // If tab bar opaque, directly stop the main content higher. If
      // translucent, let main content draw behind the tab bar but hint the
      // obstructed area.
xster's avatar
xster committed
422
      if (widget.tabBar.opaque(context)) {
423
        contentPadding = EdgeInsets.only(bottom: bottomPadding);
424
        newMediaQuery = newMediaQuery.removePadding(removeBottom: true);
425
      } else {
426 427 428
        newMediaQuery = newMediaQuery.copyWith(
          padding: newMediaQuery.padding.copyWith(
            bottom: bottomPadding,
429 430 431 432 433
          ),
        );
      }
    }

434 435
    content = MediaQuery(
      data: newMediaQuery,
436 437 438 439
      child: Padding(
        padding: contentPadding,
        child: content,
      ),
440 441
    );

xster's avatar
xster committed
442 443
    return DecoratedBox(
      decoration: BoxDecoration(
444
        color: CupertinoDynamicColor.maybeResolve(widget.backgroundColor, context)
445
            ?? CupertinoTheme.of(context).scaffoldBackgroundColor,
xster's avatar
xster committed
446 447
      ),
      child: Stack(
448 449 450 451 452 453 454 455 456 457 458
        children: <Widget>[
          // The main content being at the bottom is added to the stack first.
          content,
          MediaQuery(
            data: existingMediaQuery.copyWith(textScaleFactor: 1),
            child: Align(
              alignment: Alignment.bottomCenter,
              // Override the tab bar's currentIndex to the current tab and hook in
              // our own listener to update the [_controller.currentIndex] on top of a possibly user
              // provided callback.
              child: widget.tabBar.copyWith(
459
                currentIndex: _controller.index,
460
                onTap: (int newIndex) {
461
                  _controller.index = newIndex;
462
                  // Chain the user's original callback.
463
                  widget.tabBar.onTap?.call(newIndex);
464 465 466 467 468
                },
              ),
            ),
          ),
        ],
xster's avatar
xster committed
469
      ),
470 471
    );
  }
472 473 474

  @override
  void dispose() {
475 476
    if (widget.controller?._isDisposed == false) {
      _controller.removeListener(_onCurrentIndexChange);
477
    }
478
    _internalController?.dispose();
479 480
    super.dispose();
  }
481 482
}

483
/// A widget laying out multiple tabs with only one active tab being built
484
/// at a time and on stage. Off stage tabs' animations are stopped.
485 486
class _TabSwitchingView extends StatefulWidget {
  const _TabSwitchingView({
487 488 489
    required this.currentTabIndex,
    required this.tabCount,
    required this.tabBuilder,
490
  }) : assert(currentTabIndex != null),
491
       assert(tabCount != null && tabCount > 0),
492 493 494
       assert(tabBuilder != null);

  final int currentTabIndex;
495
  final int tabCount;
496 497 498
  final IndexedWidgetBuilder tabBuilder;

  @override
499
  _TabSwitchingViewState createState() => _TabSwitchingViewState();
500 501
}

502
class _TabSwitchingViewState extends State<_TabSwitchingView> {
503 504 505 506 507 508 509 510
  final List<bool> shouldBuildTab = <bool>[];
  final List<FocusScopeNode> tabFocusNodes = <FocusScopeNode>[];

  // When focus nodes are no longer needed, we need to dispose of them, but we
  // can't be sure that nothing else is listening to them until this widget is
  // disposed of, so when they are no longer needed, we move them to this list,
  // and dispose of them when we dispose of this widget.
  final List<FocusScopeNode> discardedNodes = <FocusScopeNode>[];
511 512 513 514

  @override
  void initState() {
    super.initState();
515
    shouldBuildTab.addAll(List<bool>.filled(widget.tabCount, false));
516 517 518 519 520 521 522 523 524 525 526
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _focusActiveTab();
  }

  @override
  void didUpdateWidget(_TabSwitchingView oldWidget) {
    super.didUpdateWidget(oldWidget);
527 528 529 530 531 532

    // Only partially invalidate the tabs cache to avoid breaking the current
    // behavior. We assume that the only possible change is either:
    // - new tabs are appended to the tab list, or
    // - some trailing tabs are removed.
    // If the above assumption is not true, some tabs may lose their state.
533
    final int lengthDiff = widget.tabCount - shouldBuildTab.length;
534 535 536
    if (lengthDiff > 0) {
      shouldBuildTab.addAll(List<bool>.filled(lengthDiff, false));
    } else if (lengthDiff < 0) {
537
      shouldBuildTab.removeRange(widget.tabCount, shouldBuildTab.length);
538
    }
539 540 541
    _focusActiveTab();
  }

542 543
  // Will focus the active tab if the FocusScope above it has focus already.  If
  // not, then it will just mark it as the preferred focus for that scope.
544
  void _focusActiveTab() {
545 546 547 548 549 550 551 552
    if (tabFocusNodes.length != widget.tabCount) {
      if (tabFocusNodes.length > widget.tabCount) {
        discardedNodes.addAll(tabFocusNodes.sublist(widget.tabCount));
        tabFocusNodes.removeRange(widget.tabCount, tabFocusNodes.length);
      } else {
        tabFocusNodes.addAll(
          List<FocusScopeNode>.generate(
            widget.tabCount - tabFocusNodes.length,
553
              (int index) => FocusScopeNode(debugLabel: '$CupertinoTabScaffold Tab ${index + tabFocusNodes.length}'),
554 555 556
          ),
        );
      }
557
    }
558 559 560 561 562
    FocusScope.of(context).setFirstFocus(tabFocusNodes[widget.currentTabIndex]);
  }

  @override
  void dispose() {
563
    for (final FocusScopeNode focusScopeNode in tabFocusNodes) {
564
      focusScopeNode.dispose();
565
    }
566
    for (final FocusScopeNode focusScopeNode in discardedNodes) {
567 568
      focusScopeNode.dispose();
    }
569
    super.dispose();
570 571 572 573
  }

  @override
  Widget build(BuildContext context) {
574
    return Stack(
575
      fit: StackFit.expand,
576
      children: List<Widget>.generate(widget.tabCount, (int index) {
577
        final bool active = index == widget.currentTabIndex;
578
        shouldBuildTab[index] = active || shouldBuildTab[index];
579

najeira's avatar
najeira committed
580 581 582 583 584 585 586 587 588 589 590 591
        return HeroMode(
          enabled: active,
          child: Offstage(
            offstage: !active,
            child: TickerMode(
              enabled: active,
              child: FocusScope(
                node: tabFocusNodes[index],
                child: Builder(builder: (BuildContext context) {
                  return shouldBuildTab[index] ? widget.tabBuilder(context, index) : Container();
                }),
              ),
592
            ),
593 594 595 596 597 598
          ),
        );
      }),
    );
  }
}
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625

/// A [RestorableProperty] that knows how to store and restore a
/// [CupertinoTabController].
///
/// The [CupertinoTabController] is accessible via the [value] getter. During
/// state restoration, the property will restore [CupertinoTabController.index]
/// to the value it had when the restoration data it is getting restored from
/// was collected.
class RestorableCupertinoTabController extends RestorableChangeNotifier<CupertinoTabController> {
  /// Creates a [RestorableCupertinoTabController] to control the tab index of
  /// [CupertinoTabScaffold] and [CupertinoTabBar].
  ///
  /// The `initialIndex` must not be null and defaults to 0. The value must be
  /// greater than or equal to 0, and less than the total number of tabs.
  RestorableCupertinoTabController({ int initialIndex = 0 })
    : assert(initialIndex != null),
      assert(initialIndex >= 0),
      _initialIndex = initialIndex;

  final int _initialIndex;

  @override
  CupertinoTabController createDefaultValue() {
    return CupertinoTabController(initialIndex: _initialIndex);
  }

  @override
626 627 628
  CupertinoTabController fromPrimitives(Object? data) {
    assert(data != null);
    return CupertinoTabController(initialIndex: data! as int);
629 630 631 632 633 634 635
  }

  @override
  Object? toPrimitives() {
    return value.index;
  }
}