bottom_navigation_bar.dart 34 KB
Newer Older
1 2 3 4 5
// Copyright 2016 The Chromium 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 'dart:collection' show Queue;
6
import 'dart:math' as math;
7 8 9 10 11 12

import 'package:flutter/widgets.dart';
import 'package:vector_math/vector_math_64.dart' show Vector3;

import 'colors.dart';
import 'constants.dart';
13
import 'debug.dart';
14 15
import 'ink_well.dart';
import 'material.dart';
16
import 'material_localizations.dart';
17
import 'text_theme.dart';
18 19 20 21 22 23 24
import 'theme.dart';

/// Defines the layout and behavior of a [BottomNavigationBar].
///
/// See also:
///
///  * [BottomNavigationBar]
25
///  * [BottomNavigationBarItem]
26
///  * <https://material.io/design/components/bottom-navigation.html#specs>
27
enum BottomNavigationBarType {
28
  /// The [BottomNavigationBar]'s [BottomNavigationBarItem]s have fixed width.
29 30
  fixed,

31
  /// The location and size of the [BottomNavigationBar] [BottomNavigationBarItem]s
32
  /// animate and labels fade in when they are tapped.
33 34 35
  shifting,
}

36 37
/// A material widget that's displayed at the bottom of an app for selecting
/// among a small number of views, typically between three and five.
38
///
39
/// The bottom navigation bar consists of multiple items in the form of
40 41 42
/// text labels, icons, or both, laid out on top of a piece of material. It
/// provides quick navigation between the top-level views of an app. For larger
/// screens, side navigation may be a better fit.
43
///
44 45
/// A bottom navigation bar is usually used in conjunction with a [Scaffold],
/// where it is provided as the [Scaffold.bottomNavigationBar] argument.
46
///
47
/// The bottom navigation bar's [type] changes how its [items] are displayed.
48 49 50
/// If not specified, then it's automatically set to
/// [BottomNavigationBarType.fixed] when there are less than four items, and
/// [BottomNavigationBarType.shifting] otherwise.
51 52
///
///  * [BottomNavigationBarType.fixed], the default when there are less than
53 54 55 56
///    four [items]. The selected item is rendered with the
///    [selectedItemColor] if it's non-null, otherwise the theme's
///    [ThemeData.primaryColor] is used. If [backgroundColor] is null, The
///    navigation bar's background color defaults to the [Material] background
57 58
///    color, [ThemeData.canvasColor] (essentially opaque white).
///  * [BottomNavigationBarType.shifting], the default when there are four
59 60
///    or more [items]. If [selectedItemColor] is null, all items are rendered
///    in white. The navigation bar's background color is the same as the
61 62 63 64
///    [BottomNavigationBarItem.backgroundColor] of the selected item. In this
///    case it's assumed that each item will have a different background color
///    and that background color will contrast well with white.
///
65
/// {@tool snippet --template=stateful_widget_material}
66 67
/// This example shows a [BottomNavigationBar] as it is used within a [Scaffold]
/// widget. The [BottomNavigationBar] has three [BottomNavigationBarItem]
68
/// widgets and the [currentIndex] is set to index 0. The selected item is
69
/// amber. The `_onItemTapped` function changes the selected item's index
70
/// and displays a corresponding message in the center of the [Scaffold].
71
///
72 73 74
/// ![A scaffold with a bottom navigation bar containing three bottom navigation
/// bar items. The first one is selected.](https://flutter.github.io/assets-for-api-docs/assets/material/bottom_navigation_bar.png)
///
75
/// ```dart
76
/// int _selectedIndex = 0;
77 78 79 80 81 82 83 84 85 86 87 88 89 90
/// static const TextStyle optionStyle = TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
/// static const List<Widget> _widgetOptions = <Widget>[
///   Text(
///     'Index 0: Home',
///     style: optionStyle,
///   ),
///   Text(
///      'Index 1: Business',
///      style: optionStyle,
///   ),
///   Text(
///      'Index 2: School',
///      style: optionStyle,
///   ),
91
/// ];
92
///
93 94 95 96
/// void _onItemTapped(int index) {
///   setState(() {
///     _selectedIndex = index;
///   });
97 98
/// }
///
99 100 101 102
/// @override
/// Widget build(BuildContext context) {
///   return Scaffold(
///     appBar: AppBar(
103
///       title: const Text('BottomNavigationBar Sample'),
104 105 106 107 108
///     ),
///     body: Center(
///       child: _widgetOptions.elementAt(_selectedIndex),
///     ),
///     bottomNavigationBar: BottomNavigationBar(
109 110 111 112 113 114 115 116 117 118 119 120 121
///       items: const <BottomNavigationBarItem>[
///         BottomNavigationBarItem(
///           icon: Icon(Icons.home),
///           title: Text('Home'),
///         ),
///         BottomNavigationBarItem(
///           icon: Icon(Icons.business),
///           title: Text('Business'),
///         ),
///         BottomNavigationBarItem(
///           icon: Icon(Icons.school),
///           title: Text('School'),
///         ),
122 123
///       ],
///       currentIndex: _selectedIndex,
124
///       selectedItemColor: Colors.amber[800],
125 126 127
///       onTap: _onItemTapped,
///     ),
///   );
128 129
/// }
/// ```
130
/// {@end-tool}
131
///
132 133
/// See also:
///
134
///  * [BottomNavigationBarItem]
135
///  * [Scaffold]
136
///  * <https://material.io/design/components/bottom-navigation.html>
137
class BottomNavigationBar extends StatefulWidget {
138 139
  /// Creates a bottom navigation bar which is typically used as a
  /// [Scaffold]'s [Scaffold.bottomNavigationBar] argument.
140
  ///
141 142
  /// The length of [items] must be at least two and each item's icon and title
  /// must not be null.
143
  ///
144 145
  /// If [type] is null then [BottomNavigationBarType.fixed] is used when there
  /// are two or three [items], [BottomNavigationBarType.shifting] otherwise.
146
  ///
147 148 149
  /// The [iconSize], [selectedFontSize], [unselectedFontSize], and [elevation]
  /// arguments must be non-null and non-negative.
  ///
150 151 152 153 154 155 156 157 158 159 160
  /// If [selectedLabelStyle.color] and [unselectedLabelStyle.color] values
  /// are non-null, they will be used instead of [selectedItemColor] and
  /// [unselectedItemColor].
  ///
  /// If custom [IconThemData]s are used, you must provide both
  /// [selectedIconTheme] and [unselectedIconTheme], and both
  /// [IconThemeData.color] and [IconThemeData.size] must be set.
  ///
  /// If both [selectedLabelStyle.fontSize] and [selectedFontSize] are set,
  /// [selectedLabelStyle.fontSize] will be used.
  ///
161 162 163 164 165 166 167 168 169
  /// Only one of [selectedItemColor] and [fixedColor] can be specified. The
  /// former is preferred, [fixedColor] only exists for the sake of
  /// backwards compatibility.
  ///
  /// The [showSelectedLabels] argument must not be non-null.
  ///
  /// The [showUnselectedLabels] argument defaults to `true` if [type] is
  /// [BottomNavigationBarType.fixed] and `false` if [type] is
  /// [BottomNavigationBarType.shifting].
170 171
  BottomNavigationBar({
    Key key,
172
    @required this.items,
173
    this.onTap,
174
    this.currentIndex = 0,
175
    this.elevation = 8.0,
176
    BottomNavigationBarType type,
177 178
    Color fixedColor,
    this.backgroundColor,
179
    this.iconSize = 24.0,
180 181
    Color selectedItemColor,
    this.unselectedItemColor,
182 183
    this.selectedIconTheme = const IconThemeData(),
    this.unselectedIconTheme = const IconThemeData(),
184 185
    this.selectedFontSize = 14.0,
    this.unselectedFontSize = 12.0,
186 187
    this.selectedLabelStyle,
    this.unselectedLabelStyle,
188 189
    this.showSelectedLabels = true,
    bool showUnselectedLabels,
190 191
  }) : assert(items != null),
       assert(items.length >= 2),
192 193 194 195
       assert(
        items.every((BottomNavigationBarItem item) => item.title != null) == true,
        'Every item must have a non-null title',
       ),
196
       assert(0 <= currentIndex && currentIndex < items.length),
197 198 199
       assert(elevation != null && elevation >= 0.0),
       assert(iconSize != null && iconSize >= 0.0),
       assert(
200
         selectedItemColor == null || fixedColor == null,
201 202 203 204 205 206 207 208
         'Either selectedItemColor or fixedColor can be specified, but not both'
       ),
       assert(selectedFontSize != null && selectedFontSize >= 0.0),
       assert(unselectedFontSize != null && unselectedFontSize >= 0.0),
       assert(showSelectedLabels != null),
       type = _type(type, items),
       selectedItemColor = selectedItemColor ?? fixedColor,
       showUnselectedLabels = showUnselectedLabels ?? _defaultShowUnselected(_type(type, items)),
209
       super(key: key);
210

211 212
  /// Defines the appearance of the button items that are arrayed within the
  /// bottom navigation bar.
213
  final List<BottomNavigationBarItem> items;
214

215
  /// Called when one of the [items] is tapped.
216
  ///
217 218 219
  /// The stateful widget that creates the bottom navigation bar needs to keep
  /// track of the index of the selected [BottomNavigationBarItem] and call
  /// `setState` to rebuild the bottom navigation bar with the new [currentIndex].
220 221
  final ValueChanged<int> onTap;

222
  /// The index into [items] for the current active [BottomNavigationBarItem].
223 224
  final int currentIndex;

225 226 227 228 229 230 231
  /// The z-coordinate of this [BottomNavigationBar].
  ///
  /// If null, defaults to `8.0`.
  ///
  /// {@macro flutter.material.material.elevation}
  final double elevation;

232
  /// Defines the layout and behavior of a [BottomNavigationBar].
233
  ///
234 235
  /// See documentation for [BottomNavigationBarType] for information on the
  /// meaning of different types.
236 237
  final BottomNavigationBarType type;

238 239 240 241 242 243 244
  /// The value of [selectedItemColor].
  ///
  /// This getter only exists for backwards compatibility, the
  /// [selectedItemColor] property is preferred.
  Color get fixedColor => selectedItemColor;

  /// The color of the [BottomNavigationBar] itself.
245
  ///
246 247 248 249
  /// If [type] is [BottomNavigationBarType.shifting] and the
  /// [items]s, have [BottomNavigationBarItem.backgroundColor] set, the [item]'s
  /// backgroundColor will splash and overwrite this color.
  final Color backgroundColor;
250

251
  /// The size of all of the [BottomNavigationBarItem] icons.
252
  ///
253
  /// See [BottomNavigationBarItem.icon] for more information.
254 255
  final double iconSize;

256 257 258 259 260 261 262 263 264 265 266 267
  /// The color of the selected [BottomNavigationBarItem.icon] and
  /// [BottomNavigationBarItem.label].
  ///
  /// If null then the [ThemeData.primaryColor] is used.
  final Color selectedItemColor;

  /// The color of the unselected [BottomNavigationBarItem.icon] and
  /// [BottomNavigationBarItem.label]s.
  ///
  /// If null then the [TextTheme.caption]'s color is used.
  final Color unselectedItemColor;

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
  /// The size, opacity, and color of the icon in the currently selected
  /// [BottomNavigationBarItem.icon].
  ///
  /// If this is not provided, the size will default to [iconSize], the color
  /// will default to [selectedItemColor].
  ///
  /// It this field is provided, it must contain non-null [IconThemeData.size]
  /// and [IconThemeData.color] properties. Also, if this field is supplied,
  /// [unselectedIconTheme] must be provided.
  final IconThemeData selectedIconTheme;

  /// The size, opacity, and color of the icon in the currently unselected
  /// [BottomNavigationBarItem.icon]s
  ///
  /// If this is not provided, the size will default to [iconSize], the color
  /// will default to [unselectedItemColor].
  ///
  /// It this field is provided, it must contain non-null [IconThemeData.size]
  /// and [IconThemeData.color] properties. Also, if this field is supplied,
  /// [unselectedIconTheme] must be provided.
  final IconThemeData unselectedIconTheme;

  /// The [TextStyle] of the [BottomNavigationBarItem] labels when they are
  /// selected.
  final TextStyle selectedLabelStyle;

  /// The [TextStyle] of the [BottomNavigationBarItem] labels when they are not
  /// selected.
  final TextStyle unselectedLabelStyle;

298 299
  /// The font size of the [BottomNavigationBarItem] labels when they are selected.
  ///
300 301
  /// If [selectedLabelStyle.fontSize] is non-null, it will be used instead of this.
  ///
302 303 304 305 306 307
  /// Defaults to `14.0`.
  final double selectedFontSize;

  /// The font size of the [BottomNavigationBarItem] labels when they are not
  /// selected.
  ///
308 309
  /// If [unselectedLabelStyle.fontSize] is non-null, it will be used instead of this.
  ///
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
  /// Defaults to `12.0`.
  final double unselectedFontSize;

  /// Whether the labels are shown for the selected [BottomNavigationBarItem].
  final bool showUnselectedLabels;

  /// Whether the labels are shown for the unselected [BottomNavigationBarItem]s.
  final bool showSelectedLabels;

  // Used by the [BottomNavigationBar] constructor to set the [type] parameter.
  //
  // If type is provided, it is returned. Otherwise,
  // [BottomNavigationBarType.fixed] is used for 3 or fewer items, and
  // [BottomNavigationBarType.shifting] is used for 4+ items.
  static BottomNavigationBarType _type(
325 326
    BottomNavigationBarType type,
    List<BottomNavigationBarItem> items,
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
  ) {
    if (type != null) {
      return type;
    }
    return items.length <= 3 ? BottomNavigationBarType.fixed : BottomNavigationBarType.shifting;
  }

  // Used by the [BottomNavigationBar] constructor to set the [showUnselected]
  // parameter.
  //
  // Unselected labels are shown by default for [BottomNavigationBarType.fixed],
  // and hidden by default for [BottomNavigationBarType.shifting].
  static bool _defaultShowUnselected(BottomNavigationBarType type) {
    switch (type) {
      case BottomNavigationBarType.shifting:
        return false;
      case BottomNavigationBarType.fixed:
        return true;
    }
    assert(false);
    return false;
  }

350
  @override
351
  _BottomNavigationBarState createState() => _BottomNavigationBarState();
352 353
}

354 355 356
// This represents a single tile in the bottom navigation bar. It is intended
// to go into a flex container.
class _BottomNavigationTile extends StatelessWidget {
357
  const _BottomNavigationTile(
358 359 360 361 362 363
    this.type,
    this.item,
    this.animation,
    this.iconSize, {
    this.onTap,
    this.colorTween,
364
    this.flex,
365
    this.selected = false,
366 367 368 369
    @required this.selectedLabelStyle,
    @required this.unselectedLabelStyle,
    @required this.selectedIconTheme,
    @required this.unselectedIconTheme,
370 371
    this.showSelectedLabels,
    this.showUnselectedLabels,
372
    this.indexLabel,
373 374 375 376
    }) : assert(type != null),
         assert(item != null),
         assert(animation != null),
         assert(selected != null),
377 378
         assert(selectedLabelStyle != null),
         assert(unselectedLabelStyle != null);
379 380 381 382 383 384 385 386

  final BottomNavigationBarType type;
  final BottomNavigationBarItem item;
  final Animation<double> animation;
  final double iconSize;
  final VoidCallback onTap;
  final ColorTween colorTween;
  final double flex;
387
  final bool selected;
388 389 390 391
  final IconThemeData selectedIconTheme;
  final IconThemeData unselectedIconTheme;
  final TextStyle selectedLabelStyle;
  final TextStyle unselectedLabelStyle;
392
  final String indexLabel;
393 394
  final bool showSelectedLabels;
  final bool showUnselectedLabels;
395

396 397 398 399 400 401 402
  @override
  Widget build(BuildContext context) {
    // In order to use the flex container to grow the tile during animation, we
    // need to divide the changes in flex allotment into smaller pieces to
    // produce smooth animation. We do this by multiplying the flex value
    // (which is an integer) by a large number.
    int size;
403

404 405 406 407 408 409 410 411 412 413
    final double selectedFontSize = selectedLabelStyle.fontSize;

    final double selectedIconSize = selectedIconTheme?.size ?? iconSize;
    final double unselectedIconSize = unselectedIconTheme?.size ?? iconSize;
    // The amount that the selected icon is bigger than the unselected icons,
    // (or zero if the selected icon is not bigger than the unselected icons).
    final double selectedIconDiff = math.max(selectedIconSize - unselectedIconSize, 0);
    // The amount that the unselected icons are bigger than the selected icon,
    // (or zero if the unselected icons are not any bigger than the selected icon).
    final double unselectedIconDiff = math.max(unselectedIconSize - selectedIconSize, 0);
414 415 416 417 418

    // Defines the padding for the animating icons + labels.
    //
    // The animations go from "Unselected":
    // =======
419
    // |      <-- Padding equal to the text height + 1/2 selectedIconDiff.
420
    // |  ☆
421
    // | text <-- Invisible text + padding equal to 1/2 selectedIconDiff.
422 423 424 425 426
    // =======
    //
    // To "Selected":
    //
    // =======
427
    // |      <-- Padding equal to 1/2 text height + 1/2 unselectedIconDiff.
428 429
    // |  ☆
    // | text
430
    // |      <-- Padding equal to 1/2 text height + 1/2 unselectedIconDiff.
431
    // =======
432 433
    double bottomPadding;
    double topPadding;
434 435
    if (showSelectedLabels && !showUnselectedLabels) {
      bottomPadding = Tween<double>(
436 437
        begin: selectedIconDiff / 2.0,
        end: selectedFontSize / 2.0 - unselectedIconDiff / 2.0,
438 439
      ).evaluate(animation);
      topPadding = Tween<double>(
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
        begin: selectedFontSize + selectedIconDiff / 2.0,
        end: selectedFontSize / 2.0 - unselectedIconDiff / 2.0,
      ).evaluate(animation);
    } else if (!showSelectedLabels && !showUnselectedLabels) {
      bottomPadding = Tween<double>(
        begin: selectedIconDiff / 2.0,
        end: unselectedIconDiff / 2.0,
      ).evaluate(animation);
      topPadding = Tween<double>(
        begin: selectedFontSize + selectedIconDiff / 2.0,
        end: selectedFontSize + unselectedIconDiff / 2.0,
      ).evaluate(animation);
    } else {
      bottomPadding = Tween<double>(
        begin: selectedFontSize / 2.0 + selectedIconDiff / 2.0,
        end: selectedFontSize / 2.0 + unselectedIconDiff / 2.0,
      ).evaluate(animation);
      topPadding = Tween<double>(
        begin: selectedFontSize / 2.0 + selectedIconDiff / 2.0,
        end: selectedFontSize / 2.0 + unselectedIconDiff / 2.0,
460 461
      ).evaluate(animation);
    }
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476

    switch (type) {
      case BottomNavigationBarType.fixed:
        size = 1;
        break;
      case BottomNavigationBarType.shifting:
        size = (flex * 1000.0).round();
        break;
    }

    return Expanded(
      flex: size,
      child: Semantics(
        container: true,
        selected: selected,
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
        child: Focus(
          child: Stack(
            children: <Widget>[
              InkResponse(
                onTap: onTap,
                child: Padding(
                  padding: EdgeInsets.only(top: topPadding, bottom: bottomPadding),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      _TileIcon(
                        colorTween: colorTween,
                        animation: animation,
                        iconSize: iconSize,
                        selected: selected,
                        item: item,
                        selectedIconTheme: selectedIconTheme,
                        unselectedIconTheme: unselectedIconTheme,
                      ),
                      _Label(
                        colorTween: colorTween,
                        animation: animation,
                        item: item,
                        selectedLabelStyle: selectedLabelStyle,
                        unselectedLabelStyle: unselectedLabelStyle,
                        showSelectedLabels: showSelectedLabels,
                        showUnselectedLabels: showUnselectedLabels,
                      ),
                    ],
                  ),
509
                ),
510
              ),
511 512 513 514 515
              Semantics(
                label: indexLabel,
              ),
            ],
          ),
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
        ),
      ),
    );
  }
}


class _TileIcon extends StatelessWidget {
  const _TileIcon({
    Key key,
    @required this.colorTween,
    @required this.animation,
    @required this.iconSize,
    @required this.selected,
    @required this.item,
531 532
    @required this.selectedIconTheme,
    @required this.unselectedIconTheme,
533 534 535
  }) : assert(selected != null),
       assert(item != null),
       super(key: key);
536 537 538 539 540 541

  final ColorTween colorTween;
  final Animation<double> animation;
  final double iconSize;
  final bool selected;
  final BottomNavigationBarItem item;
542 543
  final IconThemeData selectedIconTheme;
  final IconThemeData unselectedIconTheme;
544 545 546

  @override
  Widget build(BuildContext context) {
547
    final Color iconColor = colorTween.evaluate(animation);
548 549 550 551 552 553 554 555 556 557
    final IconThemeData defaultIconTheme = IconThemeData(
      color: iconColor,
      size: iconSize,
    );
    final IconThemeData iconThemeData = IconThemeData.lerp(
      defaultIconTheme.merge(unselectedIconTheme),
      defaultIconTheme.merge(selectedIconTheme),
      animation.value,
    );

558
    return Align(
559 560
      alignment: Alignment.topCenter,
      heightFactor: 1.0,
561 562
      child: Container(
        child: IconTheme(
563
          data: iconThemeData,
564
          child: selected ? item.activeIcon : item.icon,
565 566 567 568
        ),
      ),
    );
  }
569
}
570

571 572
class _Label extends StatelessWidget {
  const _Label({
573 574 575 576
    Key key,
    @required this.colorTween,
    @required this.animation,
    @required this.item,
577 578
    @required this.selectedLabelStyle,
    @required this.unselectedLabelStyle,
579 580 581 582 583
    @required this.showSelectedLabels,
    @required this.showUnselectedLabels,
  }) : assert(colorTween != null),
       assert(animation != null),
       assert(item != null),
584 585
       assert(selectedLabelStyle != null),
       assert(unselectedLabelStyle != null),
586 587 588
       assert(showSelectedLabels != null),
       assert(showUnselectedLabels != null),
       super(key: key);
589 590 591 592

  final ColorTween colorTween;
  final Animation<double> animation;
  final BottomNavigationBarItem item;
593 594
  final TextStyle selectedLabelStyle;
  final TextStyle unselectedLabelStyle;
595 596
  final bool showSelectedLabels;
  final bool showUnselectedLabels;
597 598 599

  @override
  Widget build(BuildContext context) {
600 601 602 603 604 605 606 607
    final double selectedFontSize = selectedLabelStyle.fontSize;
    final double unselectedFontSize = unselectedLabelStyle.fontSize;

    final TextStyle customStyle = TextStyle.lerp(
      unselectedLabelStyle,
      selectedLabelStyle,
      animation.value,
    );
608
    Widget text = DefaultTextStyle.merge(
609
      style: customStyle.copyWith(
610 611 612 613 614 615 616 617 618 619 620 621 622
        fontSize: selectedFontSize,
        color: colorTween.evaluate(animation),
      ),
      // The font size should grow here when active, but because of the way
      // font rendering works, it doesn't grow smoothly if we just animate
      // the font size, so we use a transform instead.
      child: Transform(
        transform: Matrix4.diagonal3(
          Vector3.all(
            Tween<double>(
              begin: unselectedFontSize / selectedFontSize,
              end: 1.0,
            ).evaluate(animation),
623 624
          ),
        ),
625 626
        alignment: Alignment.bottomCenter,
        child: item.title,
627 628 629
      ),
    );

630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
    if (!showUnselectedLabels && !showSelectedLabels) {
      // Never show any labels.
      text = Opacity(
        alwaysIncludeSemantics: true,
        opacity: 0.0,
        child: text,
      );
    } else if (!showUnselectedLabels) {
      // Fade selected labels in.
      text = FadeTransition(
        alwaysIncludeSemantics: true,
        opacity: animation,
        child: text,
      );
    } else if (!showSelectedLabels) {
      // Fade selected labels out.
      text = FadeTransition(
        alwaysIncludeSemantics: true,
        opacity: Tween<double>(begin: 1.0, end: 0.0).animate(animation),
        child: text,
      );
    }
652

653
    return Align(
654 655
      alignment: Alignment.bottomCenter,
      heightFactor: 1.0,
656
      child: Container(child: text),
657 658 659 660
    );
  }
}

661
class _BottomNavigationBarState extends State<BottomNavigationBar> with TickerProviderStateMixin {
662
  List<AnimationController> _controllers = <AnimationController>[];
663
  List<CurvedAnimation> _animations;
664 665

  // A queue of color splashes currently being animated.
666
  final Queue<_Circle> _circles = Queue<_Circle>();
667

668 669 670 671
  // Last splash circle's color, and the final color of the control after
  // animation is complete.
  Color _backgroundColor;

672
  static final Animatable<double> _flexTween = Tween<double>(begin: 1.0, end: 1.5);
673

674 675 676 677 678 679 680
  void _resetState() {
    for (AnimationController controller in _controllers)
      controller.dispose();
    for (_Circle circle in _circles)
      circle.dispose();
    _circles.clear();

681 682
    _controllers = List<AnimationController>.generate(widget.items.length, (int index) {
      return AnimationController(
683 684
        duration: kThemeAnimationDuration,
        vsync: this,
685 686
      )..addListener(_rebuild);
    });
687 688
    _animations = List<CurvedAnimation>.generate(widget.items.length, (int index) {
      return CurvedAnimation(
689 690
        parent: _controllers[index],
        curve: Curves.fastOutSlowIn,
691
        reverseCurve: Curves.fastOutSlowIn.flipped,
692 693
      );
    });
694 695
    _controllers[widget.currentIndex].value = 1.0;
    _backgroundColor = widget.items[widget.currentIndex].backgroundColor;
696 697
  }

698 699 700 701 702 703
  @override
  void initState() {
    super.initState();
    _resetState();
  }

704 705
  void _rebuild() {
    setState(() {
706
      // Rebuilding when any of the controllers tick, i.e. when the items are
707 708 709 710
      // animated.
    });
  }

711 712 713 714 715 716 717
  @override
  void dispose() {
    for (AnimationController controller in _controllers)
      controller.dispose();
    for (_Circle circle in _circles)
      circle.dispose();
    super.dispose();
718 719
  }

720
  double _evaluateFlex(Animation<double> animation) => _flexTween.evaluate(animation);
721 722

  void _pushCircle(int index) {
723
    if (widget.items[index].backgroundColor != null) {
724
      _circles.add(
725
        _Circle(
726 727
          state: this,
          index: index,
728
          color: widget.items[index].backgroundColor,
729
          vsync: this,
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
        )..controller.addStatusListener(
          (AnimationStatus status) {
            switch (status) {
              case AnimationStatus.completed:
                setState(() {
                  final _Circle circle = _circles.removeFirst();
                  _backgroundColor = circle.color;
                  circle.dispose();
                });
                break;
              case AnimationStatus.dismissed:
              case AnimationStatus.forward:
              case AnimationStatus.reverse:
                break;
            }
          },
        ),
747
      );
748
    }
749 750 751
  }

  @override
752
  void didUpdateWidget(BottomNavigationBar oldWidget) {
753
    super.didUpdateWidget(oldWidget);
754 755 756 757 758 759 760

    // No animated segue if the length of the items list changes.
    if (widget.items.length != oldWidget.items.length) {
      _resetState();
      return;
    }

761
    if (widget.currentIndex != oldWidget.currentIndex) {
762 763 764 765 766 767 768
      switch (widget.type) {
        case BottomNavigationBarType.fixed:
          break;
        case BottomNavigationBarType.shifting:
          _pushCircle(widget.currentIndex);
          break;
      }
769 770
      _controllers[oldWidget.currentIndex].reverse();
      _controllers[widget.currentIndex].forward();
771 772 773
    } else {
      if (_backgroundColor != widget.items[widget.currentIndex].backgroundColor)
        _backgroundColor = widget.items[widget.currentIndex].backgroundColor;
774 775 776
    }
  }

777 778 779
  // If the given [TextStyle] has a non-null `fontSize`, it should be used.
  // Otherwise, the [selectedFontSize] parameter should be used.
  static TextStyle _effectiveTextStyle(TextStyle textStyle, double fontSize) {
780
    textStyle ??= const TextStyle();
781 782 783 784
    // Prefer the font size on textStyle if present.
    return textStyle.fontSize == null ? textStyle.copyWith(fontSize: fontSize) : textStyle;
  }

785
  List<Widget> _createTiles() {
786 787
    final MaterialLocalizations localizations = MaterialLocalizations.of(context);
    assert(localizations != null);
788 789 790

    final ThemeData themeData = Theme.of(context);

791 792 793 794 795
    final TextStyle effectiveSelectedLabelStyle =
      _effectiveTextStyle(widget.selectedLabelStyle, widget.selectedFontSize);
    final TextStyle effectiveUnselectedLabelStyle =
      _effectiveTextStyle(widget.unselectedLabelStyle, widget.unselectedFontSize);

796 797 798 799 800 801 802 803 804 805 806
    Color themeColor;
    switch (themeData.brightness) {
      case Brightness.light:
        themeColor = themeData.primaryColor;
        break;
      case Brightness.dark:
        themeColor = themeData.accentColor;
        break;
    }

    ColorTween colorTween;
807
    switch (widget.type) {
808
      case BottomNavigationBarType.fixed:
809 810 811
        colorTween = ColorTween(
          begin: widget.unselectedItemColor ?? themeData.textTheme.caption.color,
          end: widget.selectedItemColor ?? widget.fixedColor ?? themeColor,
812 813 814
        );
        break;
      case BottomNavigationBarType.shifting:
815 816 817 818
        colorTween = ColorTween(
          begin: widget.unselectedItemColor ?? Colors.white,
          end: widget.selectedItemColor ?? Colors.white,
        );
819 820
        break;
    }
821 822 823 824 825 826 827 828

    final List<Widget> tiles = <Widget>[];
    for (int i = 0; i < widget.items.length; i++) {
      tiles.add(_BottomNavigationTile(
        widget.type,
        widget.items[i],
        _animations[i],
        widget.iconSize,
829 830 831 832
        selectedIconTheme: widget.selectedIconTheme,
        unselectedIconTheme: widget.unselectedIconTheme,
        selectedLabelStyle: effectiveSelectedLabelStyle,
        unselectedLabelStyle: effectiveUnselectedLabelStyle,
833 834 835 836 837 838 839 840 841 842 843 844 845
        onTap: () {
          if (widget.onTap != null)
            widget.onTap(i);
        },
        colorTween: colorTween,
        flex: _evaluateFlex(_animations[i]),
        selected: i == widget.currentIndex,
        showSelectedLabels: widget.showSelectedLabels,
        showUnselectedLabels: widget.showUnselectedLabels,
        indexLabel: localizations.tabLabel(tabIndex: i + 1, tabCount: widget.items.length),
      ));
    }
    return tiles;
846 847 848 849 850
  }

  Widget _createContainer(List<Widget> tiles) {
    return DefaultTextStyle.merge(
      overflow: TextOverflow.ellipsis,
851
      child: Row(
852 853 854 855 856
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: tiles,
      ),
    );
  }
857

858 859
  @override
  Widget build(BuildContext context) {
860
    assert(debugCheckHasDirectionality(context));
861
    assert(debugCheckHasMaterialLocalizations(context));
862
    assert(debugCheckHasMediaQuery(context));
863 864

    // Labels apply up to _bottomMargin padding. Remainder is media padding.
865
    final double additionalBottomPadding = math.max(MediaQuery.of(context).padding.bottom - widget.selectedFontSize / 2.0, 0.0);
866 867 868
    Color backgroundColor;
    switch (widget.type) {
      case BottomNavigationBarType.fixed:
869
        backgroundColor = widget.backgroundColor;
870 871 872 873 874
        break;
      case BottomNavigationBarType.shifting:
        backgroundColor = _backgroundColor;
        break;
    }
875
    return Semantics(
876
      explicitChildNodes: true,
877
      child: Material(
878
        elevation: widget.elevation,
879 880 881 882 883 884 885
        color: backgroundColor,
        child: ConstrainedBox(
          constraints: BoxConstraints(minHeight: kBottomNavigationBarHeight + additionalBottomPadding),
          child: CustomPaint(
            painter: _RadialPainter(
              circles: _circles.toList(),
              textDirection: Directionality.of(context),
886
            ),
887 888 889 890 891 892 893 894
            child: Material( // Splashes.
              type: MaterialType.transparency,
              child: Padding(
                padding: EdgeInsets.only(bottom: additionalBottomPadding),
                child: MediaQuery.removePadding(
                  context: context,
                  removeBottom: true,
                  child: _createContainer(_createTiles()),
895
                ),
896
              ),
897
            ),
898
          ),
899
        ),
900
      ),
901 902 903 904
    );
  }
}

905
// Describes an animating color splash circle.
906 907
class _Circle {
  _Circle({
908 909 910
    @required this.state,
    @required this.index,
    @required this.color,
911
    @required TickerProvider vsync,
912 913 914
  }) : assert(state != null),
       assert(index != null),
       assert(color != null) {
915
    controller = AnimationController(
916 917
      duration: kThemeAnimationDuration,
      vsync: vsync,
918
    );
919
    animation = CurvedAnimation(
920
      parent: controller,
921
      curve: Curves.fastOutSlowIn,
922 923 924 925
    );
    controller.forward();
  }

926
  final _BottomNavigationBarState state;
927 928 929 930 931
  final int index;
  final Color color;
  AnimationController controller;
  CurvedAnimation animation;

932
  double get horizontalLeadingOffset {
933 934 935
    double weightSum(Iterable<Animation<double>> animations) {
      // We're adding flex values instead of animation values to produce correct
      // ratios.
936
      return animations.map<double>(state._evaluateFlex).fold<double>(0.0, (double sum, double value) => sum + value);
937 938 939
    }

    final double allWeights = weightSum(state._animations);
940 941
    // These weights sum to the start edge of the indexed item.
    final double leadingWeights = weightSum(state._animations.sublist(0, index));
942 943

    // Add half of its flex value in order to get to the center.
944
    return (leadingWeights + state._evaluateFlex(state._animations[index]) / 2.0) / allWeights;
945 946 947 948 949 950 951
  }

  void dispose() {
    controller.dispose();
  }
}

952
// Paints the animating color splash circles.
953 954
class _RadialPainter extends CustomPainter {
  _RadialPainter({
955 956 957 958
    @required this.circles,
    @required this.textDirection,
  }) : assert(circles != null),
       assert(textDirection != null);
959 960

  final List<_Circle> circles;
961
  final TextDirection textDirection;
962 963

  // Computes the maximum radius attainable such that at least one of the
964 965
  // bounding rectangle's corners touches the edge of the circle. Drawing a
  // circle larger than this radius is not needed, since there is no perceivable
966
  // difference within the cropped rectangle.
967 968 969 970
  static double _maxRadius(Offset center, Size size) {
    final double maxX = math.max(center.dx, size.width - center.dx);
    final double maxY = math.max(center.dy, size.height - center.dy);
    return math.sqrt(maxX * maxX + maxY * maxY);
971 972 973 974
  }

  @override
  bool shouldRepaint(_RadialPainter oldPainter) {
975 976
    if (textDirection != oldPainter.textDirection)
      return true;
977 978 979 980 981 982 983 984 985 986 987 988 989
    if (circles == oldPainter.circles)
      return false;
    if (circles.length != oldPainter.circles.length)
      return true;
    for (int i = 0; i < circles.length; i += 1)
      if (circles[i] != oldPainter.circles[i])
        return true;
    return false;
  }

  @override
  void paint(Canvas canvas, Size size) {
    for (_Circle circle in circles) {
990 991
      final Paint paint = Paint()..color = circle.color;
      final Rect rect = Rect.fromLTWH(0.0, 0.0, size.width, size.height);
992
      canvas.clipRect(rect);
993 994 995 996 997 998 999 1000 1001
      double leftFraction;
      switch (textDirection) {
        case TextDirection.rtl:
          leftFraction = 1.0 - circle.horizontalLeadingOffset;
          break;
        case TextDirection.ltr:
          leftFraction = circle.horizontalLeadingOffset;
          break;
      }
1002 1003
      final Offset center = Offset(leftFraction * size.width, size.height / 2.0);
      final Tween<double> radiusTween = Tween<double>(
1004 1005
        begin: 0.0,
        end: _maxRadius(center, size),
1006
      );
1007
      canvas.drawCircle(
1008
        center,
1009
        radiusTween.transform(circle.animation.value),
1010
        paint,
1011 1012 1013 1014
      );
    }
  }
}