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

5
import 'dart:math' as math;
6 7 8
import 'dart:ui' show ImageFilter;

import 'package:flutter/foundation.dart';
9
import 'package:flutter/rendering.dart';
10
import 'package:flutter/services.dart';
11 12
import 'package:flutter/widgets.dart';

13
import 'button.dart';
14
import 'colors.dart';
15
import 'constants.dart';
16
import 'icons.dart';
17
import 'page_scaffold.dart';
18
import 'route.dart';
xster's avatar
xster committed
19
import 'theme.dart';
20

21
/// Standard iOS navigation bar height without the status bar.
22 23
///
/// This height is constant and independent of accessibility as it is in iOS.
24
const double _kNavBarPersistentHeight = kMinInteractiveDimensionCupertino;
25

26
/// Size increase from expanding the navigation bar into an iOS-11-style large title
27
/// form in a [CustomScrollView].
28
const double _kNavBarLargeTitleHeightExtension = 52.0;
29 30

/// Number of logical pixels scrolled down before the title text is transferred
31
/// from the normal navigation bar to a big title below the navigation bar.
32 33 34 35
const double _kNavBarShowLargeTitleThreshold = 10.0;

const double _kNavBarEdgePadding = 16.0;

36 37
const double _kNavBarBackButtonTapWidth = 50.0;

38
/// Title text transfer fade.
39
const Duration _kNavBarTitleFadeDuration = Duration(milliseconds: 150);
40

41
const Color _kDefaultNavBarBorderColor = Color(0x4D000000);
42

43 44
const Border _kDefaultNavBarBorder = Border(
  bottom: BorderSide(
45 46 47 48 49 50
    color: _kDefaultNavBarBorderColor,
    width: 0.0, // One physical pixel.
    style: BorderStyle.solid,
  ),
);

51 52
// There's a single tag for all instances of navigation bars because they can
// all transition between each other (per Navigator) via Hero transitions.
53
const _HeroTag _defaultHeroTag = _HeroTag(null);
54 55

class _HeroTag {
56 57 58 59
  const _HeroTag(this.navigator);

  final NavigatorState navigator;

60 61
  // Let the Hero tag be described in tree dumps.
  @override
62 63 64 65 66 67 68 69 70 71
  String toString() => 'Default Hero tag for Cupertino navigation bars with navigator $navigator';

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) {
      return true;
    }
    if (other.runtimeType != runtimeType) {
      return false;
    }
72 73
    return other is _HeroTag
        && other.navigator == navigator;
74 75 76 77 78 79
  }

  @override
  int get hashCode {
    return identityHashCode(navigator);
  }
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
}

/// Returns `child` wrapped with background and a bottom border if background color
/// is opaque. Otherwise, also blur with [BackdropFilter].
///
/// When `updateSystemUiOverlay` is true, the nav bar will update the OS
/// status bar's color theme based on the background color of the nav bar.
Widget _wrapWithBackground({
  Border border,
  Color backgroundColor,
  Widget child,
  bool updateSystemUiOverlay = true,
}) {
  Widget result = child;
  if (updateSystemUiOverlay) {
    final bool darkBackground = backgroundColor.computeLuminance() < 0.179;
    final SystemUiOverlayStyle overlayStyle = darkBackground
        ? SystemUiOverlayStyle.light
        : SystemUiOverlayStyle.dark;
99
    result = AnnotatedRegion<SystemUiOverlayStyle>(
100 101 102 103 104
      value: overlayStyle,
      sized: true,
      child: result,
    );
  }
105 106
  final DecoratedBox childWithBackground = DecoratedBox(
    decoration: BoxDecoration(
107 108 109 110 111 112 113 114 115
      border: border,
      color: backgroundColor,
    ),
    child: result,
  );

  if (backgroundColor.alpha == 0xFF)
    return childWithBackground;

116 117 118
  return ClipRect(
    child: BackdropFilter(
      filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
119 120 121 122 123
      child: childWithBackground,
    ),
  );
}

xster's avatar
xster committed
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
// This exists to support backward compatibility with arguments like
// `actionsForegroundColor`. CupertinoThemes can be used to support these
// scenarios now. To support `actionsForegroundColor`, the nav bar rewraps
// its children with a CupertinoTheme.
Widget _wrapActiveColor(Color color, BuildContext context, Widget child) {
  if (color == null) {
    return child;
  }

  return CupertinoTheme(
    data: CupertinoTheme.of(context).copyWith(primaryColor: color),
    child: child,
  );
}

139 140 141 142 143 144 145 146 147 148
// Whether the current route supports nav bar hero transitions from or to.
bool _isTransitionable(BuildContext context) {
  final ModalRoute<dynamic> route = ModalRoute.of(context);

  // Fullscreen dialogs never transitions their nav bar with other push-style
  // pages' nav bars or with other fullscreen dialog pages on the way in or on
  // the way out.
  return route is PageRoute && !route.fullscreenDialog;
}

149
/// An iOS-styled navigation bar.
150 151 152 153 154 155 156
///
/// The navigation bar is a toolbar that minimally consists of a widget, normally
/// a page title, in the [middle] of the toolbar.
///
/// It also supports a [leading] and [trailing] widget before and after the
/// [middle] widget while keeping the [middle] widget centered.
///
157 158 159 160
/// The [leading] widget will automatically be a back chevron icon button (or a
/// close button in case of a fullscreen dialog) to pop the current route if none
/// is provided and [automaticallyImplyLeading] is true (true by default).
///
161
/// The [middle] widget will automatically be a title text from the current
162 163
/// [CupertinoPageRoute] if none is provided and [automaticallyImplyMiddle] is
/// true (true by default).
164
///
165 166 167 168 169
/// It should be placed at top of the screen and automatically accounts for
/// the OS's status bar.
///
/// If the given [backgroundColor]'s opacity is not 1.0 (which is the case by
/// default), it will produce a blurring effect to the content behind it.
170
///
171
/// When [transitionBetweenRoutes] is true, this navigation bar will transition
172
/// on top of the routes instead of inside them if the route being transitioned
173 174 175 176 177
/// to also has a [CupertinoNavigationBar] or a [CupertinoSliverNavigationBar]
/// with [transitionBetweenRoutes] set to true. If [transitionBetweenRoutes] is
/// true, none of the [Widget] parameters can contain a key in its subtree since
/// that widget will exist in multiple places in the tree simultaneously.
///
178 179 180 181 182
/// By default, only one [CupertinoNavigationBar] or [CupertinoSliverNavigationBar]
/// should be present in each [PageRoute] to support the default transitions.
/// Use [transitionBetweenRoutes] or [heroTag] to customize the transition
/// behavior for multiple navigation bars per route.
///
183 184 185 186 187 188 189 190
/// When used in a [CupertinoPageScaffold], [CupertinoPageScaffold.navigationBar]
/// 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 `navigationBar`'s components inside a [MediaQuery]
/// with the desired [MediaQueryData.textScaleFactor] value. The text scale factor
/// value from the operating system can be retrieved in many ways, such as querying
/// [MediaQuery.textScaleFactorOf] against [CupertinoApp]'s [BuildContext].
///
191 192
/// See also:
///
193 194 195 196
///  * [CupertinoPageScaffold], a page layout helper typically hosting the
///    [CupertinoNavigationBar].
///  * [CupertinoSliverNavigationBar] for a navigation bar to be placed in a
///    scrolling list and that supports iOS-11-style large titles.
197
class CupertinoNavigationBar extends StatefulWidget implements ObstructingPreferredSizeWidget {
198
  /// Creates a navigation bar in the iOS style.
199 200 201
  const CupertinoNavigationBar({
    Key key,
    this.leading,
202
    this.automaticallyImplyLeading = true,
203 204
    this.automaticallyImplyMiddle = true,
    this.previousPageTitle,
205
    this.middle,
206
    this.trailing,
207
    this.border = _kDefaultNavBarBorder,
xster's avatar
xster committed
208
    this.backgroundColor,
209
    this.padding,
xster's avatar
xster committed
210
    this.actionsForegroundColor,
211 212
    this.transitionBetweenRoutes = true,
    this.heroTag = _defaultHeroTag,
213
  }) : assert(automaticallyImplyLeading != null),
214
       assert(automaticallyImplyMiddle != null),
215 216 217 218 219 220 221 222 223 224 225
       assert(transitionBetweenRoutes != null),
       assert(
         heroTag != null,
         'heroTag cannot be null. Use transitionBetweenRoutes = false to '
         'disable Hero transition on this navigation bar.'
       ),
       assert(
         !transitionBetweenRoutes || identical(heroTag, _defaultHeroTag),
         'Cannot specify a heroTag override if this navigation bar does not '
         'transition due to transitionBetweenRoutes = false.'
       ),
226
       super(key: key);
227

228
  /// {@template flutter.cupertino.navBar.leading}
229
  /// Widget to place at the start of the navigation bar. Normally a back button
230
  /// for a normal page or a cancel button for full page dialogs.
231 232 233 234
  ///
  /// If null and [automaticallyImplyLeading] is true, an appropriate button
  /// will be automatically created.
  /// {@endtemplate}
235 236
  final Widget leading;

237
  /// {@template flutter.cupertino.navBar.automaticallyImplyLeading}
238 239 240 241 242
  /// Controls whether we should try to imply the leading widget if null.
  ///
  /// If true and [leading] is null, automatically try to deduce what the [leading]
  /// widget should be. If [leading] widget is not null, this parameter has no effect.
  ///
243 244 245 246 247 248 249 250 251
  /// Specifically this navigation bar will:
  ///
  /// 1. Show a 'Close' button if the current route is a `fullscreenDialog`.
  /// 2. Show a back chevron with [previousPageTitle] if [previousPageTitle] is
  ///    not null.
  /// 3. Show a back chevron with the previous route's `title` if the current
  ///    route is a [CupertinoPageRoute] and the previous route is also a
  ///    [CupertinoPageRoute].
  ///
252
  /// This value cannot be null.
253
  /// {@endtemplate}
254 255
  final bool automaticallyImplyLeading;

256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
  /// Controls whether we should try to imply the middle widget if null.
  ///
  /// If true and [middle] is null, automatically fill in a [Text] widget with
  /// the current route's `title` if the route is a [CupertinoPageRoute].
  /// If [middle] widget is not null, this parameter has no effect.
  ///
  /// This value cannot be null.
  final bool automaticallyImplyMiddle;

  /// {@template flutter.cupertino.navBar.previousPageTitle}
  /// Manually specify the previous route's title when automatically implying
  /// the leading back button.
  ///
  /// Overrides the text shown with the back chevron instead of automatically
  /// showing the previous [CupertinoPageRoute]'s `title` when
  /// [automaticallyImplyLeading] is true.
  ///
  /// Has no effect when [leading] is not null or if [automaticallyImplyLeading]
  /// is false.
  /// {@endtemplate}
  final String previousPageTitle;

278
  /// Widget to place in the middle of the navigation bar. Normally a title or
279
  /// a segmented control.
280 281 282 283
  ///
  /// If null and [automaticallyImplyMiddle] is true, an appropriate [Text]
  /// title will be created if the current route is a [CupertinoPageRoute] and
  /// has a `title`.
284 285
  final Widget middle;

286
  /// {@template flutter.cupertino.navBar.trailing}
287
  /// Widget to place at the end of the navigation bar. Normally additional actions
288
  /// taken on the page such as a search or edit function.
289
  /// {@endtemplate}
290 291
  final Widget trailing;

292 293
  // TODO(xster): https://github.com/flutter/flutter/issues/10469 implement
  // support for double row navigation bars.
294

295
  /// {@template flutter.cupertino.navBar.backgroundColor}
296
  /// The background color of the navigation bar. If it contains transparency, the
297 298
  /// tab bar will automatically produce a blurring effect to the content
  /// behind it.
xster's avatar
xster committed
299 300
  ///
  /// Defaults to [CupertinoTheme]'s `barBackgroundColor` if null.
301
  /// {@endtemplate}
302 303
  final Color backgroundColor;

304
  /// {@template flutter.cupertino.navBar.padding}
305 306 307 308 309 310 311 312 313 314 315
  /// Padding for the contents of the navigation bar.
  ///
  /// If null, the navigation bar will adopt the following defaults:
  ///
  ///  * Vertically, contents will be sized to the same height as the navigation
  ///    bar itself minus the status bar.
  ///  * Horizontally, padding will be 16 pixels according to iOS specifications
  ///    unless the leading widget is an automatically inserted back button, in
  ///    which case the padding will be 0.
  ///
  /// Vertical padding won't change the height of the nav bar.
316
  /// {@endtemplate}
317 318
  final EdgeInsetsDirectional padding;

319
  /// {@template flutter.cupertino.navBar.border}
320 321 322
  /// The border of the navigation bar. By default renders a single pixel bottom border side.
  ///
  /// If a border is null, the navigation bar will not display a border.
323
  /// {@endtemplate}
324 325
  final Border border;

xster's avatar
xster committed
326
  /// {@template flutter.cupertino.navBar.actionsForegroundColor}
327
  /// Default color used for text and icons of the [leading] and [trailing]
328
  /// widgets in the navigation bar.
329
  ///
xster's avatar
xster committed
330 331 332
  /// Defaults to the `primaryColor` of the [CupertinoTheme] when null.
  /// {@endtemplate}
  ///
333 334
  /// The default color for text in the [middle] slot is always black, as per
  /// iOS standard design.
335 336 337 338
  @Deprecated(
    'Use CupertinoTheme and primaryColor to propagate color. '
    'This feature was deprecated after v1.1.2.'
  )
339 340
  final Color actionsForegroundColor;

341 342 343 344 345 346 347 348
  /// {@template flutter.cupertino.navBar.transitionBetweenRoutes}
  /// Whether to transition between navigation bars.
  ///
  /// When [transitionBetweenRoutes] is true, this navigation bar will transition
  /// on top of the routes instead of inside it if the route being transitioned
  /// to also has a [CupertinoNavigationBar] or a [CupertinoSliverNavigationBar]
  /// with [transitionBetweenRoutes] set to true.
  ///
xster's avatar
xster committed
349 350 351 352
  /// This transition will also occur on edge back swipe gestures like on iOS
  /// but only if the previous page below has `maintainState` set to true on the
  /// [PageRoute].
  ///
353 354 355 356 357 358 359 360 361 362 363
  /// When set to true, only one navigation bar can be present per route unless
  /// [heroTag] is also set.
  ///
  /// This value defaults to true and cannot be null.
  /// {@endtemplate}
  final bool transitionBetweenRoutes;

  /// {@template flutter.cupertino.navBar.heroTag}
  /// Tag for the navigation bar's Hero widget if [transitionBetweenRoutes] is true.
  ///
  /// Defaults to a common tag between all [CupertinoNavigationBar] and
364 365 366 367 368 369 370
  /// [CupertinoSliverNavigationBar] instances of the same [Navigator]. With the
  /// default tag, all navigation bars of the same navigator can transition
  /// between each other as long as there's only one navigation bar per route.
  ///
  /// This [heroTag] can be overridden to manually handle having multiple
  /// navigation bars per route or to transition between multiple
  /// [Navigator]s.
371 372 373 374 375 376
  ///
  /// Cannot be null. To disable Hero transitions for this navigation bar,
  /// set [transitionBetweenRoutes] to false.
  /// {@endtemplate}
  final Object heroTag;

377
  /// True if the navigation bar's background color has no transparency.
378
  @override
379 380 381 382 383
  bool shouldFullyObstruct(BuildContext context) {
    final Color backgroundColor = CupertinoDynamicColor.resolve(this.backgroundColor, context)
                               ?? CupertinoTheme.of(context).barBackgroundColor;
    return backgroundColor.alpha == 0xFF;
  }
384

385
  @override
386
  Size get preferredSize {
387
    return const Size.fromHeight(_kNavBarPersistentHeight);
388
  }
389

390 391
  @override
  _CupertinoNavigationBarState createState() {
392
    return _CupertinoNavigationBarState();
393 394 395 396 397 398 399 400 401 402 403 404
  }
}

// A state class exists for the nav bar so that the keys of its sub-components
// don't change when rebuilding the nav bar, causing the sub-components to
// lose their own states.
class _CupertinoNavigationBarState extends State<CupertinoNavigationBar> {
  _NavigationBarStaticComponentsKeys keys;

  @override
  void initState() {
    super.initState();
405
    keys = _NavigationBarStaticComponentsKeys();
406 407
  }

408 409
  @override
  Widget build(BuildContext context) {
xster's avatar
xster committed
410
    final Color backgroundColor =
411
      CupertinoDynamicColor.resolve(widget.backgroundColor, context) ?? CupertinoTheme.of(context).barBackgroundColor;
xster's avatar
xster committed
412

413
    final _NavigationBarStaticComponents components = _NavigationBarStaticComponents(
414 415 416 417 418 419 420 421 422 423 424
      keys: keys,
      route: ModalRoute.of(context),
      userLeading: widget.leading,
      automaticallyImplyLeading: widget.automaticallyImplyLeading,
      automaticallyImplyTitle: widget.automaticallyImplyMiddle,
      previousPageTitle: widget.previousPageTitle,
      userMiddle: widget.middle,
      userTrailing: widget.trailing,
      padding: widget.padding,
      userLargeTitle: null,
      large: false,
425 426
    );

427 428
    final Widget navBar = _wrapWithBackground(
      border: widget.border,
xster's avatar
xster committed
429 430 431 432 433 434 435
      backgroundColor: backgroundColor,
      child: DefaultTextStyle(
        style: CupertinoTheme.of(context).textTheme.textStyle,
        child: _PersistentNavigationBar(
          components: components,
          padding: widget.padding,
        ),
436 437 438
      ),
    );

439 440 441 442
    final Color actionsForegroundColor = CupertinoDynamicColor.resolve(
      widget.actionsForegroundColor, // ignore: deprecated_member_use_from_same_package
      context,
    );
443
    if (!widget.transitionBetweenRoutes || !_isTransitionable(context)) {
xster's avatar
xster committed
444
      // Lint ignore to maintain backward compatibility.
445
      return _wrapActiveColor(actionsForegroundColor, context, navBar);
446 447
    }

xster's avatar
xster committed
448 449
    return _wrapActiveColor(
      // Lint ignore to maintain backward compatibility.
450
      actionsForegroundColor,
xster's avatar
xster committed
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
      context,
      Builder(
        // Get the context that might have a possibly changed CupertinoTheme.
        builder: (BuildContext context) {
          return Hero(
            tag: widget.heroTag == _defaultHeroTag
                ? _HeroTag(Navigator.of(context))
                : widget.heroTag,
            createRectTween: _linearTranslateWithLargestRectSizeTween,
            placeholderBuilder: _navBarHeroLaunchPadBuilder,
            flightShuttleBuilder: _navBarHeroFlightShuttleBuilder,
            transitionOnUserGestures: true,
            child: _TransitionableNavigationBar(
              componentsKeys: keys,
              backgroundColor: backgroundColor,
              backButtonTextStyle: CupertinoTheme.of(context).textTheme.navActionTextStyle,
              titleTextStyle: CupertinoTheme.of(context).textTheme.navTitleTextStyle,
              largeTitleTextStyle: null,
              border: widget.border,
              hasUserMiddle: widget.middle != null,
              largeExpanded: false,
              child: navBar,
            ),
          );
        },
476
      ),
477
    );
478 479
  }
}
480

481
/// An iOS-styled navigation bar with iOS-11-style large titles using slivers.
482 483 484 485
///
/// The [CupertinoSliverNavigationBar] must be placed in a sliver group such
/// as the [CustomScrollView].
///
486 487
/// This navigation bar consists of two sections, a pinned static section on top
/// and a sliding section containing iOS-11-style large title below it.
488 489
///
/// It should be placed at top of the screen and automatically accounts for
490
/// the iOS status bar.
491
///
492 493
/// Minimally, a [largeTitle] widget will appear in the middle of the app bar
/// when the sliver is collapsed and transfer to the area below in larger font
494 495
/// when the sliver is expanded.
///
496 497
/// For advanced uses, an optional [middle] widget can be supplied to show a
/// different widget in the middle of the navigation bar when the sliver is collapsed.
498
///
499 500 501 502 503 504 505
/// Like [CupertinoNavigationBar], it also supports a [leading] and [trailing]
/// widget on the static section on top that remains while scrolling.
///
/// The [leading] widget will automatically be a back chevron icon button (or a
/// close button in case of a fullscreen dialog) to pop the current route if none
/// is provided and [automaticallyImplyLeading] is true (true by default).
///
506
/// The [largeTitle] widget will automatically be a title text from the current
507 508
/// [CupertinoPageRoute] if none is provided and [automaticallyImplyTitle] is
/// true (true by default).
509
///
510
/// When [transitionBetweenRoutes] is true, this navigation bar will transition
511
/// on top of the routes instead of inside them if the route being transitioned
512 513 514 515 516 517
/// to also has a [CupertinoNavigationBar] or a [CupertinoSliverNavigationBar]
/// with [transitionBetweenRoutes] set to true. If [transitionBetweenRoutes] is
/// true, none of the [Widget] parameters can contain any [GlobalKey]s in their
/// subtrees since those widgets will exist in multiple places in the tree
/// simultaneously.
///
518 519 520 521 522
/// By default, only one [CupertinoNavigationBar] or [CupertinoSliverNavigationBar]
/// should be present in each [PageRoute] to support the default transitions.
/// Use [transitionBetweenRoutes] or [heroTag] to customize the transition
/// behavior for multiple navigation bars per route.
///
523 524 525 526 527 528 529 530
/// `CupertinoSliverNavigationBar` has its text scale factor set to 1.0 by default
/// 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
/// `CupertinoSliverNavigationBar`'s components inside a [MediaQuery] with the
/// desired [MediaQueryData.textScaleFactor] value. The text scale factor value
/// from the operating system can be retrieved in many ways, such as querying
/// [MediaQuery.textScaleFactorOf] against [CupertinoApp]'s [BuildContext].
///
531 532
/// See also:
///
533 534
///  * [CupertinoNavigationBar], an iOS navigation bar for use on non-scrolling
///    pages.
535
class CupertinoSliverNavigationBar extends StatefulWidget {
536 537 538
  /// Creates a navigation bar for scrolling lists.
  ///
  /// The [largeTitle] argument is required and must not be null.
539 540
  const CupertinoSliverNavigationBar({
    Key key,
541
    this.largeTitle,
542
    this.leading,
543
    this.automaticallyImplyLeading = true,
544 545
    this.automaticallyImplyTitle = true,
    this.previousPageTitle,
546 547
    this.middle,
    this.trailing,
548
    this.border = _kDefaultNavBarBorder,
xster's avatar
xster committed
549
    this.backgroundColor,
550
    this.padding,
xster's avatar
xster committed
551
    this.actionsForegroundColor,
552 553
    this.transitionBetweenRoutes = true,
    this.heroTag = _defaultHeroTag,
554 555
  }) : assert(automaticallyImplyLeading != null),
       assert(automaticallyImplyTitle != null),
556 557 558 559 560 561
       assert(
         automaticallyImplyTitle == true || largeTitle != null,
         'No largeTitle has been provided but automaticallyImplyTitle is also '
         'false. Either provide a largeTitle or set automaticallyImplyTitle to '
         'true.'
       ),
562 563 564 565 566
       super(key: key);

  /// The navigation bar's title.
  ///
  /// This text will appear in the top static navigation bar when collapsed and
567 568 569 570 571 572 573 574 575 576 577
  /// below the navigation bar, in a larger font, when expanded.
  ///
  /// A suitable [DefaultTextStyle] is provided around this widget as it is
  /// moved around, to change its font size.
  ///
  /// If [middle] is null, then the [largeTitle] widget will be inserted into
  /// the tree in two places when transitioning from the collapsed state to the
  /// expanded state. It is therefore imperative that this subtree not contain
  /// any [GlobalKey]s, and that it not rely on maintaining state (for example,
  /// animations will not survive the transition from one location to the other,
  /// and may in fact be visible in two places at once during the transition).
578 579 580 581
  ///
  /// If null and [automaticallyImplyTitle] is true, an appropriate [Text]
  /// title will be created if the current route is a [CupertinoPageRoute] and
  /// has a `title`.
582 583 584
  ///
  /// This parameter must either be non-null or the route must have a title
  /// ([CupertinoPageRoute.title]) and [automaticallyImplyTitle] must be true.
585 586
  final Widget largeTitle;

587
  /// {@macro flutter.cupertino.navBar.leading}
588 589 590 591
  ///
  /// This widget is visible in both collapsed and expanded states.
  final Widget leading;

592 593 594 595
  /// {@macro flutter.cupertino.navBar.automaticallyImplyLeading}
  final bool automaticallyImplyLeading;

  /// Controls whether we should try to imply the [largeTitle] widget if null.
596
  ///
597 598 599
  /// If true and [largeTitle] is null, automatically fill in a [Text] widget
  /// with the current route's `title` if the route is a [CupertinoPageRoute].
  /// If [largeTitle] widget is not null, this parameter has no effect.
600 601
  ///
  /// This value cannot be null.
602 603 604 605
  final bool automaticallyImplyTitle;

  /// {@macro flutter.cupertino.navBar.previousPageTitle}
  final String previousPageTitle;
606

607 608
  /// A widget to place in the middle of the static navigation bar instead of
  /// the [largeTitle].
609 610
  ///
  /// This widget is visible in both collapsed and expanded states. The text
611 612
  /// supplied in [largeTitle] will no longer appear in collapsed state if a
  /// [middle] widget is provided.
613 614
  final Widget middle;

615
  /// {@macro flutter.cupertino.navBar.trailing}
616 617 618 619
  ///
  /// This widget is visible in both collapsed and expanded states.
  final Widget trailing;

620 621 622 623
  /// {@macro flutter.cupertino.navBar.backgroundColor}
  final Color backgroundColor;

  /// {@macro flutter.cupertino.navBar.padding}
624 625
  final EdgeInsetsDirectional padding;

626
  /// {@macro flutter.cupertino.navBar.border}
627 628
  final Border border;

xster's avatar
xster committed
629
  /// {@macro flutter.cupertino.navBar.actionsForegroundColor}
630
  ///
631
  /// The default color for text in the [largeTitle] slot is always black, as per
632
  /// iOS standard design.
633 634 635 636
  @Deprecated(
    'Use CupertinoTheme and primaryColor to propagate color. '
    'This feature was deprecated after v1.1.2.'
  )
637 638
  final Color actionsForegroundColor;

639 640 641 642 643 644
  /// {@macro flutter.cupertino.navBar.transitionBetweenRoutes}
  final bool transitionBetweenRoutes;

  /// {@macro flutter.cupertino.navBar.heroTag}
  final Object heroTag;

645
  /// True if the navigation bar's background color has no transparency.
646 647
  bool get opaque => backgroundColor.alpha == 0xFF;

648
  @override
649
  _CupertinoSliverNavigationBarState createState() => _CupertinoSliverNavigationBarState();
650 651 652 653 654 655 656 657 658 659 660
}

// A state class exists for the nav bar so that the keys of its sub-components
// don't change when rebuilding the nav bar, causing the sub-components to
// lose their own states.
class _CupertinoSliverNavigationBarState extends State<CupertinoSliverNavigationBar> {
  _NavigationBarStaticComponentsKeys keys;

  @override
  void initState() {
    super.initState();
661
    keys = _NavigationBarStaticComponentsKeys();
662 663
  }

664 665
  @override
  Widget build(BuildContext context) {
xster's avatar
xster committed
666
    // Lint ignore to maintain backward compatibility.
667 668
    final Color actionsForegroundColor = CupertinoDynamicColor.resolve(widget.actionsForegroundColor, context)  // ignore: deprecated_member_use_from_same_package
                                       ?? CupertinoTheme.of(context).primaryColor;
xster's avatar
xster committed
669

670
    final _NavigationBarStaticComponents components = _NavigationBarStaticComponents(
671 672 673 674 675 676 677 678 679 680 681
      keys: keys,
      route: ModalRoute.of(context),
      userLeading: widget.leading,
      automaticallyImplyLeading: widget.automaticallyImplyLeading,
      automaticallyImplyTitle: widget.automaticallyImplyTitle,
      previousPageTitle: widget.previousPageTitle,
      userMiddle: widget.middle,
      userTrailing: widget.trailing,
      userLargeTitle: widget.largeTitle,
      padding: widget.padding,
      large: true,
682 683
    );

xster's avatar
xster committed
684 685
    return _wrapActiveColor(
      // Lint ignore to maintain backward compatibility.
686
      actionsForegroundColor,
xster's avatar
xster committed
687
      context,
688 689 690 691 692 693 694 695
      MediaQuery(
        data: MediaQuery.of(context).copyWith(textScaleFactor: 1),
        child: SliverPersistentHeader(
          pinned: true, // iOS navigation bars are always pinned.
          delegate: _LargeTitleNavigationBarSliverDelegate(
            keys: keys,
            components: components,
            userMiddle: widget.middle,
696
            backgroundColor: CupertinoDynamicColor.resolve(widget.backgroundColor, context) ?? CupertinoTheme.of(context).barBackgroundColor,
697 698 699 700 701 702 703 704
            border: widget.border,
            padding: widget.padding,
            actionsForegroundColor: actionsForegroundColor,
            transitionBetweenRoutes: widget.transitionBetweenRoutes,
            heroTag: widget.heroTag,
            persistentHeight: _kNavBarPersistentHeight + MediaQuery.of(context).padding.top,
            alwaysShowMiddle: widget.middle != null,
          ),
xster's avatar
xster committed
705
        ),
706 707
      ),
    );
708 709 710
  }
}

711
class _LargeTitleNavigationBarSliverDelegate
712
    extends SliverPersistentHeaderDelegate with DiagnosticableTreeMixin {
713 714 715 716 717 718 719 720 721 722
  _LargeTitleNavigationBarSliverDelegate({
    @required this.keys,
    @required this.components,
    @required this.userMiddle,
    @required this.backgroundColor,
    @required this.border,
    @required this.padding,
    @required this.actionsForegroundColor,
    @required this.transitionBetweenRoutes,
    @required this.heroTag,
723
    @required this.persistentHeight,
724 725 726 727 728 729 730 731
    @required this.alwaysShowMiddle,
  }) : assert(persistentHeight != null),
       assert(alwaysShowMiddle != null),
       assert(transitionBetweenRoutes != null);

  final _NavigationBarStaticComponentsKeys keys;
  final _NavigationBarStaticComponents components;
  final Widget userMiddle;
732 733
  final Color backgroundColor;
  final Border border;
734
  final EdgeInsetsDirectional padding;
735
  final Color actionsForegroundColor;
736 737 738 739
  final bool transitionBetweenRoutes;
  final Object heroTag;
  final double persistentHeight;
  final bool alwaysShowMiddle;
740 741 742 743 744 745 746 747 748 749 750

  @override
  double get minExtent => persistentHeight;

  @override
  double get maxExtent => persistentHeight + _kNavBarLargeTitleHeightExtension;

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    final bool showLargeTitle = shrinkOffset < maxExtent - minExtent - _kNavBarShowLargeTitleThreshold;

751
    final _PersistentNavigationBar persistentNavigationBar =
752
        _PersistentNavigationBar(
753
      components: components,
754
      padding: padding,
755 756 757
      // If a user specified middle exists, always show it. Otherwise, show
      // title when sliver is collapsed.
      middleVisible: alwaysShowMiddle ? null : !showLargeTitle,
758 759
    );

760
    final Widget navBar = _wrapWithBackground(
761
      border: border,
762
      backgroundColor: CupertinoDynamicColor.resolve(backgroundColor, context),
xster's avatar
xster committed
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
      child: DefaultTextStyle(
        style: CupertinoTheme.of(context).textTheme.textStyle,
        child: Stack(
          fit: StackFit.expand,
          children: <Widget>[
            Positioned(
              top: persistentHeight,
              left: 0.0,
              right: 0.0,
              bottom: 0.0,
              child: ClipRect(
                // The large title starts at the persistent bar.
                // It's aligned with the bottom of the sliver and expands clipped
                // and behind the persistent bar.
                child: OverflowBox(
                  minHeight: 0.0,
                  maxHeight: double.infinity,
                  alignment: AlignmentDirectional.bottomStart,
                  child: Padding(
                    padding: const EdgeInsetsDirectional.only(
                      start: _kNavBarEdgePadding,
                      bottom: 8.0, // Bottom has a different padding.
                    ),
                    child: SafeArea(
                      top: false,
                      bottom: false,
                      child: AnimatedOpacity(
                        opacity: showLargeTitle ? 1.0 : 0.0,
                        duration: _kNavBarTitleFadeDuration,
                        child: Semantics(
                          header: true,
                          child: DefaultTextStyle(
                            style: CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            child: components.largeTitle,
                          ),
800 801 802 803 804 805 806
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
xster's avatar
xster committed
807 808 809 810 811 812 813 814
            Positioned(
              left: 0.0,
              right: 0.0,
              top: 0.0,
              child: persistentNavigationBar,
            ),
          ],
        ),
815 816
      ),
    );
817 818 819 820 821

    if (!transitionBetweenRoutes || !_isTransitionable(context)) {
      return navBar;
    }

822
    return Hero(
823 824 825
      tag: heroTag == _defaultHeroTag
          ? _HeroTag(Navigator.of(context))
          : heroTag,
826 827 828
      createRectTween: _linearTranslateWithLargestRectSizeTween,
      flightShuttleBuilder: _navBarHeroFlightShuttleBuilder,
      placeholderBuilder: _navBarHeroLaunchPadBuilder,
xster's avatar
xster committed
829
      transitionOnUserGestures: true,
830 831 832
      // This is all the way down here instead of being at the top level of
      // CupertinoSliverNavigationBar like CupertinoNavigationBar because it
      // needs to wrap the top level RenderBox rather than a RenderSliver.
833
      child: _TransitionableNavigationBar(
834
        componentsKeys: keys,
835
        backgroundColor: CupertinoDynamicColor.resolve(backgroundColor, context),
xster's avatar
xster committed
836 837 838
        backButtonTextStyle: CupertinoTheme.of(context).textTheme.navActionTextStyle,
        titleTextStyle: CupertinoTheme.of(context).textTheme.navTitleTextStyle,
        largeTitleTextStyle: CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle,
839 840 841 842 843 844
        border: border,
        hasUserMiddle: userMiddle != null,
        largeExpanded: showLargeTitle,
        child: navBar,
      ),
    );
845 846 847
  }

  @override
848
  bool shouldRebuild(_LargeTitleNavigationBarSliverDelegate oldDelegate) {
849
    return components != oldDelegate.components
850
        || userMiddle != oldDelegate.userMiddle
851
        || backgroundColor != oldDelegate.backgroundColor
852 853 854 855 856 857 858
        || border != oldDelegate.border
        || padding != oldDelegate.padding
        || actionsForegroundColor != oldDelegate.actionsForegroundColor
        || transitionBetweenRoutes != oldDelegate.transitionBetweenRoutes
        || persistentHeight != oldDelegate.persistentHeight
        || alwaysShowMiddle != oldDelegate.alwaysShowMiddle
        || heroTag != oldDelegate.heroTag;
859 860 861
  }
}

862
/// The top part of the navigation bar that's never scrolled away.
863
///
864
/// Consists of the entire navigation bar without background and border when used
865 866
/// without large titles. With large titles, it's the top static half that
/// doesn't scroll.
867 868
class _PersistentNavigationBar extends StatelessWidget {
  const _PersistentNavigationBar({
869
    Key key,
870
    this.components,
871
    this.padding,
872 873 874
    this.middleVisible,
  }) : super(key: key);

875
  final _NavigationBarStaticComponents components;
876

877
  final EdgeInsetsDirectional padding;
878 879 880 881
  /// Whether the middle widget has a visible animated opacity. A null value
  /// means the middle opacity will not be animated.
  final bool middleVisible;

882 883
  @override
  Widget build(BuildContext context) {
884
    Widget middle = components.middle;
885

886
    if (middle != null) {
887
      middle = DefaultTextStyle(
xster's avatar
xster committed
888
        style: CupertinoTheme.of(context).textTheme.navTitleTextStyle,
889
        child: Semantics(header: true, child: middle),
890 891 892 893 894
      );
      // When the middle's visibility can change on the fly like with large title
      // slivers, wrap with animated opacity.
      middle = middleVisible == null
        ? middle
895
        : AnimatedOpacity(
896 897 898
          opacity: middleVisible ? 1.0 : 0.0,
          duration: _kNavBarTitleFadeDuration,
          child: middle,
899
        );
900
    }
901

902 903 904
    Widget leading = components.leading;
    final Widget backChevron = components.backChevron;
    final Widget backLabel = components.backLabel;
905

906
    if (leading == null && backChevron != null && backLabel != null) {
907
      leading = CupertinoNavigationBarBackButton._assemble(
908 909
        backChevron,
        backLabel,
910
      );
911
    }
912

913
    Widget paddedToolbar = NavigationToolbar(
914 915 916
      leading: leading,
      middle: middle,
      trailing: components.trailing,
917
      centerMiddle: true,
918
      middleSpacing: 6.0,
919 920 921
    );

    if (padding != null) {
922
      paddedToolbar = Padding(
923 924 925 926 927 928 929 930
        padding: EdgeInsets.only(
          top: padding.top,
          bottom: padding.bottom,
        ),
        child: paddedToolbar,
      );
    }

931
    return SizedBox(
932
      height: _kNavBarPersistentHeight + MediaQuery.of(context).padding.top,
933
      child: SafeArea(
934 935
        bottom: false,
        child: paddedToolbar,
936 937
      ),
    );
938 939
  }
}
940

941 942 943 944 945 946 947 948 949
// A collection of keys always used when building static routes' nav bars's
// components with _NavigationBarStaticComponents and read in
// _NavigationBarTransition in Hero flights in order to reference the components'
// RenderBoxes for their positions.
//
// These keys should never re-appear inside the Hero flights.
@immutable
class _NavigationBarStaticComponentsKeys {
  _NavigationBarStaticComponentsKeys()
950 951 952 953 954 955 956
    : navBarBoxKey = GlobalKey(debugLabel: 'Navigation bar render box'),
      leadingKey = GlobalKey(debugLabel: 'Leading'),
      backChevronKey = GlobalKey(debugLabel: 'Back chevron'),
      backLabelKey = GlobalKey(debugLabel: 'Back label'),
      middleKey = GlobalKey(debugLabel: 'Middle'),
      trailingKey = GlobalKey(debugLabel: 'Trailing'),
      largeTitleKey = GlobalKey(debugLabel: 'Large title');
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033

  final GlobalKey navBarBoxKey;
  final GlobalKey leadingKey;
  final GlobalKey backChevronKey;
  final GlobalKey backLabelKey;
  final GlobalKey middleKey;
  final GlobalKey trailingKey;
  final GlobalKey largeTitleKey;
}

// Based on various user Widgets and other parameters, construct KeyedSubtree
// components that are used in common by the CupertinoNavigationBar and
// CupertinoSliverNavigationBar. The KeyedSubtrees are inserted into static
// routes and the KeyedSubtrees' child are reused in the Hero flights.
@immutable
class _NavigationBarStaticComponents {
  _NavigationBarStaticComponents({
    @required _NavigationBarStaticComponentsKeys keys,
    @required ModalRoute<dynamic> route,
    @required Widget userLeading,
    @required bool automaticallyImplyLeading,
    @required bool automaticallyImplyTitle,
    @required String previousPageTitle,
    @required Widget userMiddle,
    @required Widget userTrailing,
    @required Widget userLargeTitle,
    @required EdgeInsetsDirectional padding,
    @required bool large,
  }) : leading = createLeading(
         leadingKey: keys.leadingKey,
         userLeading: userLeading,
         route: route,
         automaticallyImplyLeading: automaticallyImplyLeading,
         padding: padding,
       ),
       backChevron = createBackChevron(
         backChevronKey: keys.backChevronKey,
         userLeading: userLeading,
         route: route,
         automaticallyImplyLeading: automaticallyImplyLeading,
       ),
       backLabel = createBackLabel(
         backLabelKey: keys.backLabelKey,
         userLeading: userLeading,
         route: route,
         previousPageTitle: previousPageTitle,
         automaticallyImplyLeading: automaticallyImplyLeading,
       ),
       middle = createMiddle(
         middleKey: keys.middleKey,
         userMiddle: userMiddle,
         userLargeTitle: userLargeTitle,
         route: route,
         automaticallyImplyTitle: automaticallyImplyTitle,
         large: large,
       ),
       trailing = createTrailing(
         trailingKey: keys.trailingKey,
         userTrailing: userTrailing,
         padding: padding,
       ),
       largeTitle = createLargeTitle(
         largeTitleKey: keys.largeTitleKey,
         userLargeTitle: userLargeTitle,
         route: route,
         automaticImplyTitle: automaticallyImplyTitle,
         large: large,
       );

  static Widget _derivedTitle({
    bool automaticallyImplyTitle,
    ModalRoute<dynamic> currentRoute,
  }) {
    // Auto use the CupertinoPageRoute's title if middle not provided.
    if (automaticallyImplyTitle &&
        currentRoute is CupertinoPageRoute &&
        currentRoute.title != null) {
1034
      return Text(currentRoute.title);
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
    }

    return null;
  }

  final KeyedSubtree leading;
  static KeyedSubtree createLeading({
    @required GlobalKey leadingKey,
    @required Widget userLeading,
    @required ModalRoute<dynamic> route,
    @required bool automaticallyImplyLeading,
    @required EdgeInsetsDirectional padding,
  }) {
    Widget leadingContent;

    if (userLeading != null) {
      leadingContent = userLeading;
    } else if (
      automaticallyImplyLeading &&
      route is PageRoute &&
      route.canPop &&
      route.fullscreenDialog
    ) {
1058
      leadingContent = CupertinoButton(
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
        child: const Text('Close'),
        padding: EdgeInsets.zero,
        onPressed: () { route.navigator.maybePop(); },
      );
    }

    if (leadingContent == null) {
      return null;
    }

1069
    return KeyedSubtree(
1070
      key: leadingKey,
1071 1072
      child: Padding(
        padding: EdgeInsetsDirectional.only(
1073 1074
          start: padding?.start ?? _kNavBarEdgePadding,
        ),
xster's avatar
xster committed
1075 1076 1077
        child: IconTheme.merge(
          data: const IconThemeData(
            size: 32.0,
1078
          ),
xster's avatar
xster committed
1079
          child: leadingContent,
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
        ),
      ),
    );
  }

  final KeyedSubtree backChevron;
  static KeyedSubtree createBackChevron({
    @required GlobalKey backChevronKey,
    @required Widget userLeading,
    @required ModalRoute<dynamic> route,
    @required bool automaticallyImplyLeading,
  }) {
    if (
      userLeading != null ||
      !automaticallyImplyLeading ||
      route == null ||
      !route.canPop ||
      (route is PageRoute && route.fullscreenDialog)
    ) {
      return null;
    }

1102
    return KeyedSubtree(key: backChevronKey, child: const _BackChevron());
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
  }

  /// This widget is not decorated with a font since the font style could
  /// animate during transitions.
  final KeyedSubtree backLabel;
  static KeyedSubtree createBackLabel({
    @required GlobalKey backLabelKey,
    @required Widget userLeading,
    @required ModalRoute<dynamic> route,
    @required bool automaticallyImplyLeading,
    @required String previousPageTitle,
  }) {
    if (
      userLeading != null ||
      !automaticallyImplyLeading ||
      route == null ||
      !route.canPop ||
      (route is PageRoute && route.fullscreenDialog)
    ) {
      return null;
    }

1125
    return KeyedSubtree(
1126
      key: backLabelKey,
1127
      child: _BackLabel(
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
        specifiedPreviousTitle: previousPageTitle,
        route: route,
      ),
    );
  }

  /// This widget is not decorated with a font since the font style could
  /// animate during transitions.
  final KeyedSubtree middle;
  static KeyedSubtree createMiddle({
    @required GlobalKey middleKey,
    @required Widget userMiddle,
    @required Widget userLargeTitle,
    @required bool large,
    @required bool automaticallyImplyTitle,
    @required ModalRoute<dynamic> route,
  }) {
    Widget middleContent = userMiddle;

    if (large) {
      middleContent ??= userLargeTitle;
    }

    middleContent ??= _derivedTitle(
      automaticallyImplyTitle: automaticallyImplyTitle,
      currentRoute: route,
    );

    if (middleContent == null) {
      return null;
    }

1160
    return KeyedSubtree(
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
      key: middleKey,
      child: middleContent,
    );
  }

  final KeyedSubtree trailing;
  static KeyedSubtree createTrailing({
    @required GlobalKey trailingKey,
    @required Widget userTrailing,
    @required EdgeInsetsDirectional padding,
  }) {
    if (userTrailing == null) {
      return null;
    }

1176
    return KeyedSubtree(
1177
      key: trailingKey,
1178 1179
      child: Padding(
        padding: EdgeInsetsDirectional.only(
1180 1181
          end: padding?.end ?? _kNavBarEdgePadding,
        ),
xster's avatar
xster committed
1182 1183 1184
        child: IconTheme.merge(
          data: const IconThemeData(
            size: 32.0,
1185
          ),
xster's avatar
xster committed
1186
          child: userTrailing,
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
        ),
      ),
    );
  }

  /// This widget is not decorated with a font since the font style could
  /// animate during transitions.
  final KeyedSubtree largeTitle;
  static KeyedSubtree createLargeTitle({
    @required GlobalKey largeTitleKey,
    @required Widget userLargeTitle,
    @required bool large,
    @required bool automaticImplyTitle,
    @required ModalRoute<dynamic> route,
  }) {
    if (!large) {
      return null;
    }

    final Widget largeTitleContent = userLargeTitle ?? _derivedTitle(
      automaticallyImplyTitle: automaticImplyTitle,
      currentRoute: route,
    );

    assert(
      largeTitleContent != null,
      'largeTitle was not provided and there was no title from the route.',
    );

1216
    return KeyedSubtree(
1217 1218 1219 1220 1221 1222
      key: largeTitleKey,
      child: largeTitleContent,
    );
  }
}

1223 1224 1225 1226 1227 1228
/// A nav bar back button typically used in [CupertinoNavigationBar].
///
/// This is automatically inserted into [CupertinoNavigationBar] and
/// [CupertinoSliverNavigationBar]'s `leading` slot when
/// `automaticallyImplyLeading` is true.
///
1229 1230 1231 1232
/// When manually inserted, the [CupertinoNavigationBarBackButton] should only
/// be used in routes that can be popped unless a custom [onPressed] is
/// provided.
///
1233 1234 1235 1236 1237 1238 1239 1240 1241
/// Shows a back chevron and the previous route's title when available from
/// the previous [CupertinoPageRoute.title]. If [previousPageTitle] is specified,
/// it will be shown instead.
class CupertinoNavigationBarBackButton extends StatelessWidget {
  /// Construct a [CupertinoNavigationBarBackButton] that can be used to pop
  /// the current route.
  ///
  /// The [color] parameter must not be null.
  const CupertinoNavigationBarBackButton({
xster's avatar
xster committed
1242
    this.color,
1243
    this.previousPageTitle,
1244
    this.onPressed,
1245
  }) : _backChevron = null,
xster's avatar
xster committed
1246
       _backLabel = null;
1247 1248 1249 1250 1251 1252 1253

  // Allow the back chevron and label to be separately created (and keyed)
  // because they animate separately during page transitions.
  const CupertinoNavigationBarBackButton._assemble(
    this._backChevron,
    this._backLabel,
  ) : previousPageTitle = null,
1254 1255
      color = null,
      onPressed = null;
1256 1257

  /// The [Color] of the back button.
1258
  ///
xster's avatar
xster committed
1259 1260 1261
  /// Can be used to override the color of the back button chevron and label.
  ///
  /// Defaults to [CupertinoTheme]'s `primaryColor` if null.
1262
  final Color color;
1263

1264 1265 1266 1267
  /// An override for showing the previous route's title. If null, it will be
  /// automatically derived from [CupertinoPageRoute.title] if the current and
  /// previous routes are both [CupertinoPageRoute]s.
  final String previousPageTitle;
1268

1269 1270 1271 1272
  /// An override callback to perform instead of the default behavior which is
  /// to pop the [Navigator].
  ///
  /// It can, for instance, be used to pop the platform's navigation stack
1273 1274
  /// via [SystemNavigator] instead of Flutter's [Navigator] in add-to-app
  /// situations.
1275 1276 1277 1278
  ///
  /// Defaults to null.
  final VoidCallback onPressed;

1279 1280 1281 1282
  final Widget _backChevron;

  final Widget _backLabel;

1283 1284 1285
  @override
  Widget build(BuildContext context) {
    final ModalRoute<dynamic> currentRoute = ModalRoute.of(context);
1286 1287 1288 1289 1290 1291
    if (onPressed == null) {
      assert(
        currentRoute?.canPop == true,
        'CupertinoNavigationBarBackButton should only be used in routes that can be popped',
      );
    }
1292

xster's avatar
xster committed
1293 1294
    TextStyle actionTextStyle = CupertinoTheme.of(context).textTheme.navActionTextStyle;
    if (color != null) {
1295
      actionTextStyle = actionTextStyle.copyWith(color: CupertinoDynamicColor.resolve(color, context));
xster's avatar
xster committed
1296 1297
    }

1298 1299
    return CupertinoButton(
      child: Semantics(
1300 1301 1302 1303
        container: true,
        excludeSemantics: true,
        label: 'Back',
        button: true,
xster's avatar
xster committed
1304 1305 1306 1307
        child: DefaultTextStyle(
          style: actionTextStyle,
          child: ConstrainedBox(
            constraints: const BoxConstraints(minWidth: _kNavBarBackButtonTapWidth),
1308
            child: Row(
1309 1310 1311 1312 1313 1314
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                const Padding(padding: EdgeInsetsDirectional.only(start: 8.0)),
                _backChevron ?? const _BackChevron(),
                const Padding(padding: EdgeInsetsDirectional.only(start: 6.0)),
1315 1316
                Flexible(
                  child: _backLabel ?? _BackLabel(
1317 1318 1319
                    specifiedPreviousTitle: previousPageTitle,
                    route: currentRoute,
                  ),
1320
                ),
1321 1322
              ],
            ),
1323 1324 1325 1326
          ),
        ),
      ),
      padding: EdgeInsets.zero,
1327 1328 1329 1330 1331 1332 1333
      onPressed: () {
        if (onPressed != null) {
          onPressed();
        } else {
          Navigator.maybePop(context);
        }
      },
1334 1335 1336
    );
  }
}
1337

1338

1339 1340
class _BackChevron extends StatelessWidget {
  const _BackChevron({ Key key }) : super(key: key);
1341 1342

  @override
1343 1344
  Widget build(BuildContext context) {
    final TextDirection textDirection = Directionality.of(context);
1345
    final TextStyle textStyle = DefaultTextStyle.of(context).style;
1346 1347 1348

    // Replicate the Icon logic here to get a tightly sized icon and add
    // custom non-square padding.
1349 1350 1351 1352
    Widget iconWidget = Text.rich(
      TextSpan(
        text: String.fromCharCode(CupertinoIcons.back.codePoint),
        style: TextStyle(
1353
          inherit: false,
1354
          color: textStyle.color,
1355 1356 1357 1358 1359 1360 1361 1362
          fontSize: 34.0,
          fontFamily: CupertinoIcons.back.fontFamily,
          package: CupertinoIcons.back.fontPackage,
        ),
      ),
    );
    switch (textDirection) {
      case TextDirection.rtl:
1363 1364
        iconWidget = Transform(
          transform: Matrix4.identity()..scale(-1.0, 1.0, 1.0),
1365 1366 1367 1368 1369 1370 1371 1372
          alignment: Alignment.center,
          transformHitTests: false,
          child: iconWidget,
        );
        break;
      case TextDirection.ltr:
        break;
    }
1373

1374 1375 1376
    return iconWidget;
  }
}
1377

1378 1379 1380 1381
/// A widget that shows next to the back chevron when `automaticallyImplyLeading`
/// is true.
class _BackLabel extends StatelessWidget {
  const _BackLabel({
1382
    Key key,
1383 1384
    @required this.specifiedPreviousTitle,
    @required this.route,
1385
  }) : super(key: key);
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395

  final String specifiedPreviousTitle;
  final ModalRoute<dynamic> route;

  // `child` is never passed in into ValueListenableBuilder so it's always
  // null here and unused.
  Widget _buildPreviousTitleWidget(BuildContext context, String previousTitle, Widget child) {
    if (previousTitle == null) {
      return const SizedBox(height: 0.0, width: 0.0);
    }
1396

1397
    Text textWidget = Text(
1398 1399 1400 1401 1402 1403 1404
      previousTitle,
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );

    if (previousTitle.length > 12) {
      textWidget = const Text('Back');
1405
    }
1406

1407
    return Align(
1408 1409 1410 1411
      alignment: AlignmentDirectional.centerStart,
      widthFactor: 1.0,
      child: textWidget,
    );
1412 1413 1414
  }

  @override
1415 1416 1417
  Widget build(BuildContext context) {
    if (specifiedPreviousTitle != null) {
      return _buildPreviousTitleWidget(context, specifiedPreviousTitle, null);
1418
    } else if (route is CupertinoPageRoute<dynamic> && !route.isFirst) {
1419
      final CupertinoPageRoute<dynamic> cupertinoRoute = route as CupertinoPageRoute<dynamic>;
1420 1421 1422
      // There is no timing issue because the previousTitle Listenable changes
      // happen during route modifications before the ValueListenableBuilder
      // is built.
1423
      return ValueListenableBuilder<String>(
1424 1425 1426 1427 1428 1429
        valueListenable: cupertinoRoute.previousTitle,
        builder: _buildPreviousTitleWidget,
      );
    } else {
      return const SizedBox(height: 0.0, width: 0.0);
    }
1430 1431
  }
}
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444

/// This should always be the first child of Hero widgets.
///
/// This class helps each Hero transition obtain the start or end navigation
/// bar's box size and the inner components of the navigation bar that will
/// move around.
///
/// It should be wrapped around the biggest [RenderBox] of the static
/// navigation bar in each route.
class _TransitionableNavigationBar extends StatelessWidget {
  _TransitionableNavigationBar({
    @required this.componentsKeys,
    @required this.backgroundColor,
xster's avatar
xster committed
1445 1446 1447
    @required this.backButtonTextStyle,
    @required this.titleTextStyle,
    @required this.largeTitleTextStyle,
1448 1449 1450 1451 1452 1453
    @required this.border,
    @required this.hasUserMiddle,
    @required this.largeExpanded,
    @required this.child,
  }) : assert(componentsKeys != null),
       assert(largeExpanded != null),
xster's avatar
xster committed
1454
       assert(!largeExpanded || largeTitleTextStyle != null),
1455 1456 1457 1458
       super(key: componentsKeys.navBarBoxKey);

  final _NavigationBarStaticComponentsKeys componentsKeys;
  final Color backgroundColor;
xster's avatar
xster committed
1459 1460 1461
  final TextStyle backButtonTextStyle;
  final TextStyle titleTextStyle;
  final TextStyle largeTitleTextStyle;
1462 1463 1464 1465 1466 1467
  final Border border;
  final bool hasUserMiddle;
  final bool largeExpanded;
  final Widget child;

  RenderBox get renderBox {
1468
    final RenderBox box = componentsKeys.navBarBoxKey.currentContext.findRenderObject() as RenderBox;
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
    assert(
      box.attached,
      '_TransitionableNavigationBar.renderBox should be called when building '
      'hero flight shuttles when the from and the to nav bar boxes are already '
      'laid out and painted.',
    );
    return box;
  }

  @override
  Widget build(BuildContext context) {
    assert(() {
      bool inHero;
      context.visitAncestorElements((Element ancestor) {
        if (ancestor is ComponentElement) {
          assert(
            ancestor.widget.runtimeType != _NavigationBarTransition,
            '_TransitionableNavigationBar should never re-appear inside '
            '_NavigationBarTransition. Keyed _TransitionableNavigationBar should '
            'only serve as anchor points in routes rather than appearing inside '
            'Hero flights themselves.',
          );
          if (ancestor.widget.runtimeType == Hero) {
            inHero = true;
          }
        }
        inHero ??= false;
        return true;
      });
      assert(
        inHero == true,
        '_TransitionableNavigationBar should only be added as the immediate '
        'child of Hero widgets.',
      );
      return true;
    }());
    return child;
  }
}

/// This class represents the widget that will be in the Hero flight instead of
/// the 2 static navigation bars by taking inner components from both.
///
/// The `topNavBar` parameter is the nav bar that was on top regardless of
/// push/pop direction.
///
/// Similarly, the `bottomNavBar` parameter is the nav bar that was at the
/// bottom regardless of the push/pop direction.
///
/// If [MediaQuery.padding] is still present in this widget's [BuildContext],
/// that padding will become part of the transitional navigation bar as well.
///
/// [MediaQuery.padding] should be consistent between the from/to routes and
/// the Hero overlay. Inconsistent [MediaQuery.padding] will produce undetermined
/// results.
class _NavigationBarTransition extends StatelessWidget {
  _NavigationBarTransition({
    @required this.animation,
1527 1528
    @required this.topNavBar,
    @required this.bottomNavBar,
1529
  }) : heightTween = Tween<double>(
1530 1531 1532
         begin: bottomNavBar.renderBox.size.height,
         end: topNavBar.renderBox.size.height,
       ),
1533
       backgroundTween = ColorTween(
1534 1535 1536
         begin: bottomNavBar.backgroundColor,
         end: topNavBar.backgroundColor,
       ),
1537
       borderTween = BorderTween(
1538 1539 1540 1541 1542
         begin: bottomNavBar.border,
         end: topNavBar.border,
       );

  final Animation<double> animation;
1543 1544
  final _TransitionableNavigationBar topNavBar;
  final _TransitionableNavigationBar bottomNavBar;
1545 1546 1547 1548 1549 1550 1551

  final Tween<double> heightTween;
  final ColorTween backgroundTween;
  final BorderTween borderTween;

  @override
  Widget build(BuildContext context) {
1552 1553 1554 1555 1556 1557 1558
    final _NavigationBarComponentsTransition componentsTransition = _NavigationBarComponentsTransition(
      animation: animation,
      bottomNavBar: bottomNavBar,
      topNavBar: topNavBar,
      directionality: Directionality.of(context),
    );

1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
    final List<Widget> children = <Widget>[
      // Draw an empty navigation bar box with changing shape behind all the
      // moving components without any components inside it itself.
      AnimatedBuilder(
        animation: animation,
        builder: (BuildContext context, Widget child) {
          return _wrapWithBackground(
            // Don't update the system status bar color mid-flight.
            updateSystemUiOverlay: false,
            backgroundColor: backgroundTween.evaluate(animation),
            border: borderTween.evaluate(animation),
1570
            child: SizedBox(
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
              height: heightTween.evaluate(animation),
              width: double.infinity,
            ),
          );
        },
      ),
      // Draw all the components on top of the empty bar box.
      componentsTransition.bottomBackChevron,
      componentsTransition.bottomBackLabel,
      componentsTransition.bottomLeading,
      componentsTransition.bottomMiddle,
      componentsTransition.bottomLargeTitle,
      componentsTransition.bottomTrailing,
      // Draw top components on top of the bottom components.
      componentsTransition.topLeading,
      componentsTransition.topBackChevron,
      componentsTransition.topBackLabel,
      componentsTransition.topMiddle,
      componentsTransition.topLargeTitle,
      componentsTransition.topTrailing,
    ];

    children.removeWhere((Widget child) => child == null);

    // The actual outer box is big enough to contain both the bottom and top
    // navigation bars. It's not a direct Rect lerp because some components
    // can actually be outside the linearly lerp'ed Rect in the middle of
    // the animation, such as the topLargeTitle.
1599
    return SizedBox(
1600 1601
      height: math.max(heightTween.begin, heightTween.end) + MediaQuery.of(context).padding.top,
      width: double.infinity,
1602
      child: Stack(
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
        children: children,
      ),
    );
  }
}

/// This class helps create widgets that are in transition based on static
/// components from the bottom and top navigation bars.
///
/// It animates these transitional components both in terms of position and
/// their appearance.
///
/// Instead of running the transitional components through their normal static
/// navigation bar layout logic, this creates transitional widgets that are based
/// on these widgets' existing render objects' layout and position.
///
/// This is possible because this widget is only used during Hero transitions
/// where both the from and to routes are already built and laid out.
///
/// The components' existing layout constraints and positions are then
/// replicated using [Positioned] or [PositionedTransition] wrappers.
///
/// This class should never return [KeyedSubtree]s created by
/// _NavigationBarStaticComponents directly. Since widgets from
/// _NavigationBarStaticComponents are still present in the widget tree during the
/// hero transitions, it would cause global key duplications. Instead, return
/// only the [KeyedSubtree]s' child.
@immutable
class _NavigationBarComponentsTransition {
  _NavigationBarComponentsTransition({
    @required this.animation,
    @required _TransitionableNavigationBar bottomNavBar,
    @required _TransitionableNavigationBar topNavBar,
1636
    @required TextDirection directionality,
1637 1638 1639 1640
  }) : bottomComponents = bottomNavBar.componentsKeys,
       topComponents = topNavBar.componentsKeys,
       bottomNavBarBox = bottomNavBar.renderBox,
       topNavBarBox = topNavBar.renderBox,
xster's avatar
xster committed
1641 1642 1643 1644 1645 1646
       bottomBackButtonTextStyle = bottomNavBar.backButtonTextStyle,
       topBackButtonTextStyle = topNavBar.backButtonTextStyle,
       bottomTitleTextStyle = bottomNavBar.titleTextStyle,
       topTitleTextStyle = topNavBar.titleTextStyle,
       bottomLargeTitleTextStyle = bottomNavBar.largeTitleTextStyle,
       topLargeTitleTextStyle = topNavBar.largeTitleTextStyle,
1647 1648 1649 1650 1651 1652
       bottomHasUserMiddle = bottomNavBar.hasUserMiddle,
       topHasUserMiddle = topNavBar.hasUserMiddle,
       bottomLargeExpanded = bottomNavBar.largeExpanded,
       topLargeExpanded = topNavBar.largeExpanded,
       transitionBox =
           // paintBounds are based on offset zero so it's ok to expand the Rects.
1653 1654
           bottomNavBar.renderBox.paintBounds.expandToInclude(topNavBar.renderBox.paintBounds),
       forwardDirection = directionality == TextDirection.ltr ? 1.0 : -1.0;
1655

1656
  static final Animatable<double> fadeOut = Tween<double>(
1657 1658 1659
    begin: 1.0,
    end: 0.0,
  );
1660
  static final Animatable<double> fadeIn = Tween<double>(
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674
    begin: 0.0,
    end: 1.0,
  );

  final Animation<double> animation;
  final _NavigationBarStaticComponentsKeys bottomComponents;
  final _NavigationBarStaticComponentsKeys topComponents;

  // These render boxes that are the ancestors of all the bottom and top
  // components are used to determine the components' relative positions inside
  // their respective navigation bars.
  final RenderBox bottomNavBarBox;
  final RenderBox topNavBarBox;

xster's avatar
xster committed
1675 1676 1677 1678 1679 1680 1681
  final TextStyle bottomBackButtonTextStyle;
  final TextStyle topBackButtonTextStyle;
  final TextStyle bottomTitleTextStyle;
  final TextStyle topTitleTextStyle;
  final TextStyle bottomLargeTitleTextStyle;
  final TextStyle topLargeTitleTextStyle;

1682 1683 1684 1685 1686 1687 1688 1689 1690
  final bool bottomHasUserMiddle;
  final bool topHasUserMiddle;
  final bool bottomLargeExpanded;
  final bool topLargeExpanded;

  // This is the outer box in which all the components will be fitted. The
  // sizing component of RelativeRects will be based on this rect's size.
  final Rect transitionBox;

1691 1692 1693
  // x-axis unity number representing the direction of growth for text.
  final double forwardDirection;

1694 1695 1696 1697 1698 1699
  // Take a widget it its original ancestor navigation bar render box and
  // translate it into a RelativeBox in the transition navigation bar box.
  RelativeRect positionInTransitionBox(
    GlobalKey key, {
    @required RenderBox from,
  }) {
1700
    final RenderBox componentBox = key.currentContext.findRenderObject() as RenderBox;
1701 1702
    assert(componentBox.attached);

1703
    return RelativeRect.fromRect(
1704 1705 1706 1707 1708 1709 1710 1711 1712
      componentBox.localToGlobal(Offset.zero, ancestor: from) & componentBox.size,
      transitionBox,
    );
  }

  // Create a Tween that moves a widget between its original position in its
  // ancestor navigation bar to another widget's position in that widget's
  // navigation bar.
  //
1713 1714
  // Anchor their positions based on the vertical middle of their respective
  // render boxes' leading edge.
1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726
  //
  // Also produce RelativeRects with sizes that would preserve the constant
  // BoxConstraints of the 'from' widget so that animating font sizes etc don't
  // produce rounding error artifacts with a linearly resizing rect.
  RelativeRectTween slideFromLeadingEdge({
    @required GlobalKey fromKey,
    @required RenderBox fromNavBarBox,
    @required GlobalKey toKey,
    @required RenderBox toNavBarBox,
  }) {
    final RelativeRect fromRect = positionInTransitionBox(fromKey, from: fromNavBarBox);

1727 1728
    final RenderBox fromBox = fromKey.currentContext.findRenderObject() as RenderBox;
    final RenderBox toBox = toKey.currentContext.findRenderObject() as RenderBox;
1729 1730 1731 1732 1733

    // We move a box with the size of the 'from' render object such that its
    // upper left corner is at the upper left corner of the 'to' render object.
    // With slight y axis adjustment for those render objects' height differences.
    Rect toRect =
1734 1735 1736 1737 1738
        toBox.localToGlobal(
          Offset.zero,
          ancestor: toNavBarBox,
        ).translate(
          0.0,
1739
          - fromBox.size.height / 2 + toBox.size.height / 2,
1740 1741
        ) & fromBox.size; // Keep the from render object's size.

1742 1743 1744 1745 1746 1747
    if (forwardDirection < 0) {
      // If RTL, move the center right to the center right instead of matching
      // the center lefts.
      toRect = toRect.translate(- fromBox.size.width + toBox.size.width, 0.0);
    }

1748
    return RelativeRectTween(
1749
        begin: fromRect,
1750
        end: RelativeRect.fromRect(toRect, transitionBox),
1751 1752 1753 1754
      );
  }

  Animation<double> fadeInFrom(double t, { Curve curve = Curves.easeIn }) {
1755 1756 1757
    return animation.drive(fadeIn.chain(
      CurveTween(curve: Interval(t, 1.0, curve: curve)),
    ));
1758 1759 1760
  }

  Animation<double> fadeOutBy(double t, { Curve curve = Curves.easeOut }) {
1761 1762 1763
    return animation.drive(fadeOut.chain(
      CurveTween(curve: Interval(0.0, t, curve: curve)),
    ));
1764 1765 1766
  }

  Widget get bottomLeading {
1767
    final KeyedSubtree bottomLeading = bottomComponents.leadingKey.currentWidget as KeyedSubtree;
1768 1769 1770 1771 1772

    if (bottomLeading == null) {
      return null;
    }

1773
    return Positioned.fromRelativeRect(
1774
      rect: positionInTransitionBox(bottomComponents.leadingKey, from: bottomNavBarBox),
1775
      child: FadeTransition(
1776 1777 1778 1779 1780 1781 1782
        opacity: fadeOutBy(0.4),
        child: bottomLeading.child,
      ),
    );
  }

  Widget get bottomBackChevron {
1783
    final KeyedSubtree bottomBackChevron = bottomComponents.backChevronKey.currentWidget as KeyedSubtree;
1784 1785 1786 1787 1788

    if (bottomBackChevron == null) {
      return null;
    }

1789
    return Positioned.fromRelativeRect(
1790
      rect: positionInTransitionBox(bottomComponents.backChevronKey, from: bottomNavBarBox),
1791
      child: FadeTransition(
1792
        opacity: fadeOutBy(0.6),
1793
        child: DefaultTextStyle(
xster's avatar
xster committed
1794
          style: bottomBackButtonTextStyle,
1795 1796 1797 1798 1799 1800 1801
          child: bottomBackChevron.child,
        ),
      ),
    );
  }

  Widget get bottomBackLabel {
1802
    final KeyedSubtree bottomBackLabel = bottomComponents.backLabelKey.currentWidget as KeyedSubtree;
1803 1804 1805 1806 1807 1808 1809

    if (bottomBackLabel == null) {
      return null;
    }

    final RelativeRect from = positionInTransitionBox(bottomComponents.backLabelKey, from: bottomNavBarBox);

1810
    // Transition away by sliding horizontally to the leading edge off of the screen.
1811
    final RelativeRectTween positionTween = RelativeRectTween(
1812
      begin: from,
1813 1814 1815 1816 1817 1818
      end: from.shift(
        Offset(
          forwardDirection * (-bottomNavBarBox.size.width / 2.0),
          0.0,
        ),
      ),
1819 1820
    );

1821
    return PositionedTransition(
1822
      rect: animation.drive(positionTween),
1823
      child: FadeTransition(
1824
        opacity: fadeOutBy(0.2),
1825
        child: DefaultTextStyle(
xster's avatar
xster committed
1826
          style: bottomBackButtonTextStyle,
1827 1828 1829 1830 1831 1832 1833
          child: bottomBackLabel.child,
        ),
      ),
    );
  }

  Widget get bottomMiddle {
1834 1835 1836
    final KeyedSubtree bottomMiddle = bottomComponents.middleKey.currentWidget as KeyedSubtree;
    final KeyedSubtree topBackLabel = topComponents.backLabelKey.currentWidget as KeyedSubtree;
    final KeyedSubtree topLeading = topComponents.leadingKey.currentWidget as KeyedSubtree;
1837 1838 1839 1840 1841 1842 1843 1844

    // The middle component is non-null when the nav bar is a large title
    // nav bar but would be invisible when expanded, therefore don't show it here.
    if (!bottomHasUserMiddle && bottomLargeExpanded) {
      return null;
    }

    if (bottomMiddle != null && topBackLabel != null) {
1845
      // Move from current position to the top page's back label position.
1846
      return PositionedTransition(
1847
        rect: animation.drive(slideFromLeadingEdge(
1848 1849 1850 1851
          fromKey: bottomComponents.middleKey,
          fromNavBarBox: bottomNavBarBox,
          toKey: topComponents.backLabelKey,
          toNavBarBox: topNavBarBox,
1852
        )),
1853
        child: FadeTransition(
1854 1855
          // A custom middle widget like a segmented control fades away faster.
          opacity: fadeOutBy(bottomHasUserMiddle ? 0.4 : 0.7),
1856
          child: Align(
1857 1858 1859
            // As the text shrinks, make sure it's still anchored to the leading
            // edge of a constantly sized outer box.
            alignment: AlignmentDirectional.centerStart,
1860
            child: DefaultTextStyleTransition(
1861
              style: animation.drive(TextStyleTween(
xster's avatar
xster committed
1862 1863
                begin: bottomTitleTextStyle,
                end: topBackButtonTextStyle,
1864
              )),
1865 1866 1867 1868 1869 1870 1871
              child: bottomMiddle.child,
            ),
          ),
        ),
      );
    }

1872 1873 1874
    // When the top page has a leading widget override (one of the few ways to
    // not have a top back label), don't move the bottom middle widget and just
    // fade.
1875
    if (bottomMiddle != null && topLeading != null) {
1876
      return Positioned.fromRelativeRect(
1877
        rect: positionInTransitionBox(bottomComponents.middleKey, from: bottomNavBarBox),
1878
        child: FadeTransition(
1879 1880
          opacity: fadeOutBy(bottomHasUserMiddle ? 0.4 : 0.7),
          // Keep the font when transitioning into a non-back label leading.
1881
          child: DefaultTextStyle(
xster's avatar
xster committed
1882
            style: bottomTitleTextStyle,
1883 1884 1885 1886 1887 1888 1889 1890 1891 1892
            child: bottomMiddle.child,
          ),
        ),
      );
    }

    return null;
  }

  Widget get bottomLargeTitle {
1893 1894 1895
    final KeyedSubtree bottomLargeTitle = bottomComponents.largeTitleKey.currentWidget as KeyedSubtree;
    final KeyedSubtree topBackLabel = topComponents.backLabelKey.currentWidget as KeyedSubtree;
    final KeyedSubtree topLeading = topComponents.leadingKey.currentWidget as KeyedSubtree;
1896 1897 1898 1899 1900 1901

    if (bottomLargeTitle == null || !bottomLargeExpanded) {
      return null;
    }

    if (bottomLargeTitle != null && topBackLabel != null) {
1902
      // Move from current position to the top page's back label position.
1903
      return PositionedTransition(
1904
        rect: animation.drive(slideFromLeadingEdge(
1905 1906 1907 1908
          fromKey: bottomComponents.largeTitleKey,
          fromNavBarBox: bottomNavBarBox,
          toKey: topComponents.backLabelKey,
          toNavBarBox: topNavBarBox,
1909
        )),
1910
        child: FadeTransition(
1911
          opacity: fadeOutBy(0.6),
1912
          child: Align(
1913 1914 1915
            // As the text shrinks, make sure it's still anchored to the leading
            // edge of a constantly sized outer box.
            alignment: AlignmentDirectional.centerStart,
1916
            child: DefaultTextStyleTransition(
1917
              style: animation.drive(TextStyleTween(
xster's avatar
xster committed
1918 1919
                begin: bottomLargeTitleTextStyle,
                end: topBackButtonTextStyle,
1920
              )),
1921 1922 1923 1924 1925 1926 1927 1928 1929 1930
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              child: bottomLargeTitle.child,
            ),
          ),
        ),
      );
    }

    if (bottomLargeTitle != null && topLeading != null) {
1931 1932
      // Unlike bottom middle, the bottom large title moves when it can't
      // transition to the top back label position.
1933 1934
      final RelativeRect from = positionInTransitionBox(bottomComponents.largeTitleKey, from: bottomNavBarBox);

1935
      final RelativeRectTween positionTween = RelativeRectTween(
1936
        begin: from,
1937 1938 1939 1940 1941 1942
        end: from.shift(
          Offset(
            forwardDirection * bottomNavBarBox.size.width / 4.0,
            0.0,
          ),
        ),
1943 1944
      );

1945 1946
      // Just shift slightly towards the trailing edge instead of moving to the
      // back label position.
1947
      return PositionedTransition(
1948
        rect: animation.drive(positionTween),
1949
        child: FadeTransition(
1950 1951
          opacity: fadeOutBy(0.4),
          // Keep the font when transitioning into a non-back-label leading.
1952
          child: DefaultTextStyle(
xster's avatar
xster committed
1953
            style: bottomLargeTitleTextStyle,
1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
            child: bottomLargeTitle.child,
          ),
        ),
      );
    }

    return null;
  }

  Widget get bottomTrailing {
1964
    final KeyedSubtree bottomTrailing = bottomComponents.trailingKey.currentWidget as KeyedSubtree;
1965 1966 1967 1968 1969

    if (bottomTrailing == null) {
      return null;
    }

1970
    return Positioned.fromRelativeRect(
1971
      rect: positionInTransitionBox(bottomComponents.trailingKey, from: bottomNavBarBox),
1972
      child: FadeTransition(
1973 1974 1975 1976 1977 1978 1979
        opacity: fadeOutBy(0.6),
        child: bottomTrailing.child,
      ),
    );
  }

  Widget get topLeading {
1980
    final KeyedSubtree topLeading = topComponents.leadingKey.currentWidget as KeyedSubtree;
1981 1982 1983 1984 1985

    if (topLeading == null) {
      return null;
    }

1986
    return Positioned.fromRelativeRect(
1987
      rect: positionInTransitionBox(topComponents.leadingKey, from: topNavBarBox),
1988
      child: FadeTransition(
1989 1990 1991 1992 1993 1994 1995
        opacity: fadeInFrom(0.6),
        child: topLeading.child,
      ),
    );
  }

  Widget get topBackChevron {
1996 1997
    final KeyedSubtree topBackChevron = topComponents.backChevronKey.currentWidget as KeyedSubtree;
    final KeyedSubtree bottomBackChevron = bottomComponents.backChevronKey.currentWidget as KeyedSubtree;
1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008

    if (topBackChevron == null) {
      return null;
    }

    final RelativeRect to = positionInTransitionBox(topComponents.backChevronKey, from: topNavBarBox);
    RelativeRect from = to;

    // If it's the first page with a back chevron, shift in slightly from the
    // right.
    if (bottomBackChevron == null) {
2009
      final RenderBox topBackChevronBox = topComponents.backChevronKey.currentContext.findRenderObject() as RenderBox;
2010 2011 2012 2013 2014 2015
      from = to.shift(
        Offset(
          forwardDirection * topBackChevronBox.size.width * 2.0,
          0.0,
        ),
      );
2016 2017
    }

2018
    final RelativeRectTween positionTween = RelativeRectTween(
2019 2020 2021 2022
      begin: from,
      end: to,
    );

2023
    return PositionedTransition(
2024
      rect: animation.drive(positionTween),
2025
      child: FadeTransition(
2026
        opacity: fadeInFrom(bottomBackChevron == null ? 0.7 : 0.4),
2027
        child: DefaultTextStyle(
xster's avatar
xster committed
2028
          style: topBackButtonTextStyle,
2029 2030 2031 2032 2033 2034 2035
          child: topBackChevron.child,
        ),
      ),
    );
  }

  Widget get topBackLabel {
2036 2037 2038
    final KeyedSubtree bottomMiddle = bottomComponents.middleKey.currentWidget as KeyedSubtree;
    final KeyedSubtree bottomLargeTitle = bottomComponents.largeTitleKey.currentWidget as KeyedSubtree;
    final KeyedSubtree topBackLabel = topComponents.backLabelKey.currentWidget as KeyedSubtree;
2039 2040 2041 2042 2043 2044

    if (topBackLabel == null) {
      return null;
    }

    final RenderAnimatedOpacity topBackLabelOpacity =
2045
        topComponents.backLabelKey.currentContext?.findAncestorRenderObjectOfType<RenderAnimatedOpacity>();
2046 2047 2048

    Animation<double> midClickOpacity;
    if (topBackLabelOpacity != null && topBackLabelOpacity.opacity.value < 1.0) {
2049
      midClickOpacity = animation.drive(Tween<double>(
2050 2051
        begin: 0.0,
        end: topBackLabelOpacity.opacity.value,
2052
      ));
2053 2054 2055 2056 2057 2058 2059 2060 2061
    }

    // Pick up from an incoming transition from the large title. This is
    // duplicated here from the bottomLargeTitle transition widget because the
    // content text might be different. For instance, if the bottomLargeTitle
    // text is too long, the topBackLabel will say 'Back' instead of the original
    // text.
    if (bottomLargeTitle != null &&
        topBackLabel != null &&
2062
        bottomLargeExpanded) {
2063
      return PositionedTransition(
2064
        rect: animation.drive(slideFromLeadingEdge(
2065 2066 2067 2068
          fromKey: bottomComponents.largeTitleKey,
          fromNavBarBox: bottomNavBarBox,
          toKey: topComponents.backLabelKey,
          toNavBarBox: topNavBarBox,
2069
        )),
2070
        child: FadeTransition(
2071
          opacity: midClickOpacity ?? fadeInFrom(0.4),
2072
          child: DefaultTextStyleTransition(
2073
            style: animation.drive(TextStyleTween(
xster's avatar
xster committed
2074 2075
              begin: bottomLargeTitleTextStyle,
              end: topBackButtonTextStyle,
2076
            )),
2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            child: topBackLabel.child,
          ),
        ),
      );
    }

    // The topBackLabel always comes from the large title first if available
    // and expanded instead of middle.
    if (bottomMiddle != null && topBackLabel != null) {
2088
      return PositionedTransition(
2089
        rect: animation.drive(slideFromLeadingEdge(
2090 2091 2092 2093
          fromKey: bottomComponents.middleKey,
          fromNavBarBox: bottomNavBarBox,
          toKey: topComponents.backLabelKey,
          toNavBarBox: topNavBarBox,
2094
        )),
2095
        child: FadeTransition(
2096
          opacity: midClickOpacity ?? fadeInFrom(0.3),
2097
          child: DefaultTextStyleTransition(
2098
            style: animation.drive(TextStyleTween(
xster's avatar
xster committed
2099 2100
              begin: bottomTitleTextStyle,
              end: topBackButtonTextStyle,
2101
            )),
2102 2103 2104 2105 2106 2107 2108 2109 2110 2111
            child: topBackLabel.child,
          ),
        ),
      );
    }

    return null;
  }

  Widget get topMiddle {
2112
    final KeyedSubtree topMiddle = topComponents.middleKey.currentWidget as KeyedSubtree;
2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126

    if (topMiddle == null) {
      return null;
    }

    // The middle component is non-null when the nav bar is a large title
    // nav bar but would be invisible when expanded, therefore don't show it here.
    if (!topHasUserMiddle && topLargeExpanded) {
      return null;
    }

    final RelativeRect to = positionInTransitionBox(topComponents.middleKey, from: topNavBarBox);

    // Shift in from the trailing edge of the screen.
2127
    final RelativeRectTween positionTween = RelativeRectTween(
2128 2129 2130 2131 2132 2133
      begin: to.shift(
        Offset(
          forwardDirection * topNavBarBox.size.width / 2.0,
          0.0,
        ),
      ),
2134 2135 2136
      end: to,
    );

2137
    return PositionedTransition(
2138
      rect: animation.drive(positionTween),
2139
      child: FadeTransition(
2140
        opacity: fadeInFrom(0.25),
2141
        child: DefaultTextStyle(
xster's avatar
xster committed
2142
          style: topTitleTextStyle,
2143 2144 2145 2146 2147 2148 2149
          child: topMiddle.child,
        ),
      ),
    );
  }

  Widget get topTrailing {
2150
    final KeyedSubtree topTrailing = topComponents.trailingKey.currentWidget as KeyedSubtree;
2151 2152 2153 2154 2155

    if (topTrailing == null) {
      return null;
    }

2156
    return Positioned.fromRelativeRect(
2157
      rect: positionInTransitionBox(topComponents.trailingKey, from: topNavBarBox),
2158
      child: FadeTransition(
2159 2160 2161 2162 2163 2164 2165
        opacity: fadeInFrom(0.4),
        child: topTrailing.child,
      ),
    );
  }

  Widget get topLargeTitle {
2166
    final KeyedSubtree topLargeTitle = topComponents.largeTitleKey.currentWidget as KeyedSubtree;
2167 2168 2169 2170 2171 2172 2173 2174

    if (topLargeTitle == null || !topLargeExpanded) {
      return null;
    }

    final RelativeRect to = positionInTransitionBox(topComponents.largeTitleKey, from: topNavBarBox);

    // Shift in from the trailing edge of the screen.
2175
    final RelativeRectTween positionTween = RelativeRectTween(
2176 2177 2178 2179 2180 2181
      begin: to.shift(
        Offset(
          forwardDirection * topNavBarBox.size.width,
          0.0,
        ),
      ),
2182 2183 2184
      end: to,
    );

2185
    return PositionedTransition(
2186
      rect: animation.drive(positionTween),
2187
      child: FadeTransition(
2188
        opacity: fadeInFrom(0.3),
2189
        child: DefaultTextStyle(
xster's avatar
xster committed
2190
          style: topLargeTitleTextStyle,
2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          child: topLargeTitle.child,
        ),
      ),
    );
  }
}

/// Navigation bars' hero rect tween that will move between the static bars
/// but keep a constant size that's the bigger of both navigation bars.
CreateRectTween _linearTranslateWithLargestRectSizeTween = (Rect begin, Rect end) {
2203
  final Size largestSize = Size(
2204 2205 2206
    math.max(begin.size.width, end.size.width),
    math.max(begin.size.height, end.size.height),
  );
2207
  return RectTween(
2208 2209 2210 2211 2212
    begin: begin.topLeft & largestSize,
    end: end.topLeft & largestSize,
  );
};

2213
final HeroPlaceholderBuilder _navBarHeroLaunchPadBuilder = (
2214
  BuildContext context,
2215
  Size heroSize,
2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229
  Widget child,
) {
  assert(child is _TransitionableNavigationBar);
  // Tree reshaping is fine here because the Heroes' child is always a
  // _TransitionableNavigationBar which has a GlobalKey.

  // Keeping the Hero subtree here is needed (instead of just swapping out the
  // anchor nav bars for fixed size boxes during flights) because the nav bar
  // and their specific component children may serve as anchor points again if
  // another mid-transition flight diversion is triggered.

  // This is ok performance-wise because static nav bars are generally cheap to
  // build and layout but expensive to GPU render (due to clips and blurs) which
  // we're skipping here.
2230
  return Visibility(
2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253
    maintainSize: true,
    maintainAnimation: true,
    maintainState: true,
    visible: false,
    child: child,
  );
};

/// Navigation bars' hero flight shuttle builder.
final HeroFlightShuttleBuilder _navBarHeroFlightShuttleBuilder = (
  BuildContext flightContext,
  Animation<double> animation,
  HeroFlightDirection flightDirection,
  BuildContext fromHeroContext,
  BuildContext toHeroContext,
) {
  assert(animation != null);
  assert(flightDirection != null);
  assert(fromHeroContext != null);
  assert(toHeroContext != null);
  assert(fromHeroContext.widget is Hero);
  assert(toHeroContext.widget is Hero);

2254 2255
  final Hero fromHeroWidget = fromHeroContext.widget as Hero;
  final Hero toHeroWidget = toHeroContext.widget as Hero;
2256 2257 2258 2259

  assert(fromHeroWidget.child is _TransitionableNavigationBar);
  assert(toHeroWidget.child is _TransitionableNavigationBar);

2260 2261
  final _TransitionableNavigationBar fromNavBar = fromHeroWidget.child as _TransitionableNavigationBar;
  final _TransitionableNavigationBar toNavBar = toHeroWidget.child as _TransitionableNavigationBar;
2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276

  assert(fromNavBar.componentsKeys != null);
  assert(toNavBar.componentsKeys != null);

  assert(
    fromNavBar.componentsKeys.navBarBoxKey.currentContext.owner != null,
    'The from nav bar to Hero must have been mounted in the previous frame',
  );
  assert(
    toNavBar.componentsKeys.navBarBoxKey.currentContext.owner != null,
    'The to nav bar to Hero must have been mounted in the previous frame',
  );

  switch (flightDirection) {
    case HeroFlightDirection.push:
2277
      return _NavigationBarTransition(
2278 2279 2280 2281 2282 2283
        animation: animation,
        bottomNavBar: fromNavBar,
        topNavBar: toNavBar,
      );
      break;
    case HeroFlightDirection.pop:
2284
      return _NavigationBarTransition(
2285 2286 2287 2288 2289
        animation: animation,
        bottomNavBar: toNavBar,
        topNavBar: fromNavBar,
      );
  }
2290
  return null;
2291
};