nav_bar.dart 85.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 _kNavBarBottomPadding = 8.0;

38 39
const double _kNavBarBackButtonTapWidth = 50.0;

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

43
const Color _kDefaultNavBarBorderColor = Color(0x4D000000);
44

45 46
const Border _kDefaultNavBarBorder = Border(
  bottom: BorderSide(
47
    color: _kDefaultNavBarBorderColor,
48
    width: 0.0, // 0.0 means one physical pixel
49 50 51
  ),
);

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

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

60
  final NavigatorState? navigator;
61

62 63
  // Let the Hero tag be described in tree dumps.
  @override
64 65 66 67 68 69 70 71 72 73
  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;
    }
74 75
    return other is _HeroTag
        && other.navigator == navigator;
76 77 78
  }

  @override
79
  int get hashCode => identityHashCode(navigator);
80 81
}

82 83 84 85 86 87 88 89 90
// An `AnimatedWidget` that imposes a fixed size on its child widget, and
// shifts the child widget in the parent stack, driven by its `offsetAnimation`
// property.
class _FixedSizeSlidingTransition extends AnimatedWidget {
  const _FixedSizeSlidingTransition({
    required this.isLTR,
    required this.offsetAnimation,
    required this.size,
    required this.child,
91
  }) : super(listenable: offsetAnimation);
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126

  // Whether the writing direction used in the navigation bar transition is
  // left-to-right.
  final bool isLTR;

  // The fixed size to impose on `child`.
  final Size size;

  // The animated offset from the top-leading corner of the stack.
  //
  // When `isLTR` is true, the `Offset` is the position of the child widget in
  // the stack render box's regular coordinate space.
  //
  // When `isLTR` is false, the coordinate system is flipped around the
  // horizontal axis and the origin is set to the top right corner of the render
  // boxes. In other words, this parameter describes the offset from the top
  // right corner of the stack, to the top right corner of the child widget, and
  // the x-axis runs right to left.
  final Animation<Offset> offsetAnimation;

  final Widget child;

  @override
  Widget build(BuildContext context) {
    return Positioned(
      top: offsetAnimation.value.dy,
      left: isLTR ? offsetAnimation.value.dx : null,
      right: isLTR ? null : offsetAnimation.value.dx,
      width: size.width,
      height: size.height,
      child: child,
    );
  }
}

127 128 129 130 131 132
/// 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({
133 134 135 136
  Border? border,
  required Color backgroundColor,
  Brightness? brightness,
  required Widget child,
137 138 139 140
  bool updateSystemUiOverlay = true,
}) {
  Widget result = child;
  if (updateSystemUiOverlay) {
141 142
    final bool isDark = backgroundColor.computeLuminance() < 0.179;
    final Brightness newBrightness = brightness ?? (isDark ? Brightness.dark : Brightness.light);
143
    final SystemUiOverlayStyle overlayStyle;
144 145 146 147 148 149
    switch (newBrightness) {
      case Brightness.dark:
        overlayStyle = SystemUiOverlayStyle.light;
      case Brightness.light:
        overlayStyle = SystemUiOverlayStyle.dark;
    }
150 151 152 153 154 155 156
    // [SystemUiOverlayStyle.light] and [SystemUiOverlayStyle.dark] set some system
    // navigation bar properties,
    // Before https://github.com/flutter/flutter/pull/104827 those properties
    // had no effect, now they are used if there is no AnnotatedRegion on the
    // bottom of the screen.
    // For backward compatibility, create a `SystemUiOverlayStyle` without the
    // system navigation bar properties.
157
    result = AnnotatedRegion<SystemUiOverlayStyle>(
158 159 160 161 162 163
      value: SystemUiOverlayStyle(
        statusBarColor: overlayStyle.statusBarColor,
        statusBarBrightness: overlayStyle.statusBarBrightness,
        statusBarIconBrightness: overlayStyle.statusBarIconBrightness,
        systemStatusBarContrastEnforced: overlayStyle.systemStatusBarContrastEnforced,
      ),
164 165 166
      child: result,
    );
  }
167 168
  final DecoratedBox childWithBackground = DecoratedBox(
    decoration: BoxDecoration(
169 170 171 172 173 174
      border: border,
      color: backgroundColor,
    ),
    child: result,
  );

175
  if (backgroundColor.alpha == 0xFF) {
176
    return childWithBackground;
177
  }
178

179 180 181
  return ClipRect(
    child: BackdropFilter(
      filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
182 183 184 185 186 187 188
      child: childWithBackground,
    ),
  );
}

// Whether the current route supports nav bar hero transitions from or to.
bool _isTransitionable(BuildContext context) {
189
  final ModalRoute<dynamic>? route = ModalRoute.of(context);
190 191 192 193 194 195 196

  // 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;
}

197
/// An iOS-styled navigation bar.
198 199 200 201 202 203 204
///
/// 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.
///
205 206 207 208
/// 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).
///
209
/// The [middle] widget will automatically be a title text from the current
210 211
/// [CupertinoPageRoute] if none is provided and [automaticallyImplyMiddle] is
/// true (true by default).
212
///
213 214 215 216 217
/// 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.
218
///
219
/// When [transitionBetweenRoutes] is true, this navigation bar will transition
220
/// on top of the routes instead of inside them if the route being transitioned
221 222 223 224 225
/// 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.
///
226 227 228 229 230
/// 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.
///
231
/// When used in a [CupertinoPageScaffold], [CupertinoPageScaffold.navigationBar]
232 233 234
/// disables text scaling to match the native iOS behavior. To override
/// this behavior, wrap each of the `navigationBar`'s components inside a
/// [MediaQuery] with the desired [TextScaler].
235
///
236
/// {@tool dartpad}
237 238 239 240
/// This example shows a [CupertinoNavigationBar] placed in a [CupertinoPageScaffold].
/// Since [backgroundColor]'s opacity is not 1.0, there is a blur effect and
/// content slides underneath.
///
241
/// ** See code in examples/api/lib/cupertino/nav_bar/cupertino_navigation_bar.0.dart **
242 243
/// {@end-tool}
///
244 245
/// See also:
///
246 247 248 249
///  * [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.
250
///  * <https://developer.apple.com/design/human-interface-guidelines/ios/bars/navigation-bars/>
251
class CupertinoNavigationBar extends StatefulWidget implements ObstructingPreferredSizeWidget {
252
  /// Creates a navigation bar in the iOS style.
253
  const CupertinoNavigationBar({
254
    super.key,
255
    this.leading,
256
    this.automaticallyImplyLeading = true,
257 258
    this.automaticallyImplyMiddle = true,
    this.previousPageTitle,
259
    this.middle,
260
    this.trailing,
261
    this.border = _kDefaultNavBarBorder,
xster's avatar
xster committed
262
    this.backgroundColor,
263
    this.brightness,
264
    this.padding,
265 266
    this.transitionBetweenRoutes = true,
    this.heroTag = _defaultHeroTag,
267
  }) : assert(
268 269
         !transitionBetweenRoutes || identical(heroTag, _defaultHeroTag),
         'Cannot specify a heroTag override if this navigation bar does not '
270
         'transition due to transitionBetweenRoutes = false.',
271
       );
272

273
  /// {@template flutter.cupertino.CupertinoNavigationBar.leading}
274
  /// Widget to place at the start of the navigation bar. Normally a back button
275
  /// for a normal page or a cancel button for full page dialogs.
276 277 278 279
  ///
  /// If null and [automaticallyImplyLeading] is true, an appropriate button
  /// will be automatically created.
  /// {@endtemplate}
280
  final Widget? leading;
281

282
  /// {@template flutter.cupertino.CupertinoNavigationBar.automaticallyImplyLeading}
283 284 285 286 287
  /// 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.
  ///
288 289 290 291 292 293 294 295 296
  /// 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].
  ///
297
  /// This value cannot be null.
298
  /// {@endtemplate}
299 300
  final bool automaticallyImplyLeading;

301 302 303 304 305 306 307 308 309
  /// 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;

310
  /// {@template flutter.cupertino.CupertinoNavigationBar.previousPageTitle}
311 312 313 314 315 316 317 318 319 320
  /// 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}
321
  final String? previousPageTitle;
322

323
  /// Widget to place in the middle of the navigation bar. Normally a title or
324
  /// a segmented control.
325 326 327 328
  ///
  /// If null and [automaticallyImplyMiddle] is true, an appropriate [Text]
  /// title will be created if the current route is a [CupertinoPageRoute] and
  /// has a `title`.
329
  final Widget? middle;
330

331
  /// {@template flutter.cupertino.CupertinoNavigationBar.trailing}
332
  /// Widget to place at the end of the navigation bar. Normally additional actions
333
  /// taken on the page such as a search or edit function.
334
  /// {@endtemplate}
335
  final Widget? trailing;
336

337 338
  // TODO(xster): https://github.com/flutter/flutter/issues/10469 implement
  // support for double row navigation bars.
339

340
  /// {@template flutter.cupertino.CupertinoNavigationBar.backgroundColor}
341
  /// The background color of the navigation bar. If it contains transparency, the
342 343
  /// tab bar will automatically produce a blurring effect to the content
  /// behind it.
xster's avatar
xster committed
344 345
  ///
  /// Defaults to [CupertinoTheme]'s `barBackgroundColor` if null.
346
  /// {@endtemplate}
347
  final Color? backgroundColor;
348

349
  /// {@template flutter.cupertino.CupertinoNavigationBar.brightness}
350 351 352 353 354 355 356 357 358
  /// The brightness of the specified [backgroundColor].
  ///
  /// Setting this value changes the style of the system status bar. Typically
  /// used to increase the contrast ratio of the system status bar over
  /// [backgroundColor].
  ///
  /// If set to null, the value of the property will be inferred from the relative
  /// luminance of [backgroundColor].
  /// {@endtemplate}
359
  final Brightness? brightness;
360

361
  /// {@template flutter.cupertino.CupertinoNavigationBar.padding}
362 363 364 365 366 367 368 369 370 371 372
  /// 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.
373
  /// {@endtemplate}
374
  final EdgeInsetsDirectional? padding;
375

376
  /// {@template flutter.cupertino.CupertinoNavigationBar.border}
377 378 379
  /// 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.
380
  /// {@endtemplate}
381
  final Border? border;
382

383
  /// {@template flutter.cupertino.CupertinoNavigationBar.transitionBetweenRoutes}
384 385 386 387 388 389 390
  /// 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
391 392 393 394
  /// 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].
  ///
395 396 397 398 399 400 401
  /// 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;

402
  /// {@template flutter.cupertino.CupertinoNavigationBar.heroTag}
403 404 405
  /// Tag for the navigation bar's Hero widget if [transitionBetweenRoutes] is true.
  ///
  /// Defaults to a common tag between all [CupertinoNavigationBar] and
406 407 408 409 410 411 412
  /// [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.
413 414 415 416 417 418
  ///
  /// Cannot be null. To disable Hero transitions for this navigation bar,
  /// set [transitionBetweenRoutes] to false.
  /// {@endtemplate}
  final Object heroTag;

419
  /// True if the navigation bar's background color has no transparency.
420
  @override
421
  bool shouldFullyObstruct(BuildContext context) {
422
    final Color backgroundColor = CupertinoDynamicColor.maybeResolve(this.backgroundColor, context)
423 424 425
                               ?? CupertinoTheme.of(context).barBackgroundColor;
    return backgroundColor.alpha == 0xFF;
  }
426

427
  @override
428
  Size get preferredSize {
429
    return const Size.fromHeight(_kNavBarPersistentHeight);
430
  }
431

432
  @override
433
  State<CupertinoNavigationBar> createState() => _CupertinoNavigationBarState();
434 435 436 437 438 439
}

// 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> {
440
  late _NavigationBarStaticComponentsKeys keys;
441 442 443 444

  @override
  void initState() {
    super.initState();
445
    keys = _NavigationBarStaticComponentsKeys();
446 447
  }

448 449
  @override
  Widget build(BuildContext context) {
xster's avatar
xster committed
450
    final Color backgroundColor =
451
      CupertinoDynamicColor.maybeResolve(widget.backgroundColor, context) ?? CupertinoTheme.of(context).barBackgroundColor;
xster's avatar
xster committed
452

453
    final _NavigationBarStaticComponents components = _NavigationBarStaticComponents(
454 455 456 457 458 459 460 461 462 463 464
      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,
465 466
    );

467 468
    final Widget navBar = _wrapWithBackground(
      border: widget.border,
xster's avatar
xster committed
469
      backgroundColor: backgroundColor,
470
      brightness: widget.brightness,
xster's avatar
xster committed
471 472 473 474 475 476
      child: DefaultTextStyle(
        style: CupertinoTheme.of(context).textTheme.textStyle,
        child: _PersistentNavigationBar(
          components: components,
          padding: widget.padding,
        ),
477 478 479 480
      ),
    );

    if (!widget.transitionBetweenRoutes || !_isTransitionable(context)) {
xster's avatar
xster committed
481
      // Lint ignore to maintain backward compatibility.
482
      return navBar;
483 484
    }

485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
    return 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,
          ),
        );
      },
509
    );
510 511
  }
}
512

513
/// An iOS-styled navigation bar with iOS-11-style large titles using slivers.
514 515 516 517
///
/// The [CupertinoSliverNavigationBar] must be placed in a sliver group such
/// as the [CustomScrollView].
///
518 519
/// 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.
520 521
///
/// It should be placed at top of the screen and automatically accounts for
522
/// the iOS status bar.
523
///
524 525
/// 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
526 527
/// when the sliver is expanded.
///
528 529
/// 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.
530
///
531 532 533 534 535 536 537
/// 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).
///
538
/// The [largeTitle] widget will automatically be a title text from the current
539 540
/// [CupertinoPageRoute] if none is provided and [automaticallyImplyTitle] is
/// true (true by default).
541
///
542
/// When [transitionBetweenRoutes] is true, this navigation bar will transition
543
/// on top of the routes instead of inside them if the route being transitioned
544 545 546 547 548 549
/// 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.
///
550 551 552 553 554
/// 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.
///
555 556
/// [CupertinoSliverNavigationBar] by default disables text scaling to match the
/// native iOS behavior. To override this behavior, wrap each of the
557
/// [CupertinoSliverNavigationBar]'s components inside a [MediaQuery] with the
558
/// desired [TextScaler].
559
///
560 561 562
/// The [stretch] parameter determines whether the nav bar should stretch to
/// fill the over-scroll area. The nav bar can still expand and contract as the
/// user scrolls, but it will also stretch when the user over-scrolls if the
563
/// [stretch] value is `true`. Defaults to `false`.
564
///
565 566 567 568 569 570
/// {@tool dartpad}
/// This example shows [CupertinoSliverNavigationBar] in action inside a [CustomScrollView].
///
/// ** See code in examples/api/lib/cupertino/nav_bar/cupertino_sliver_nav_bar.0.dart **
/// {@end-tool}
///
571 572
/// See also:
///
573 574
///  * [CupertinoNavigationBar], an iOS navigation bar for use on non-scrolling
///    pages.
575
///  * [CustomScrollView], a ScrollView that creates custom scroll effects using slivers.
576
///  * <https://developer.apple.com/design/human-interface-guidelines/ios/bars/navigation-bars/>
577
class CupertinoSliverNavigationBar extends StatefulWidget {
578 579 580
  /// Creates a navigation bar for scrolling lists.
  ///
  /// The [largeTitle] argument is required and must not be null.
581
  const CupertinoSliverNavigationBar({
582
    super.key,
583
    this.largeTitle,
584
    this.leading,
585
    this.automaticallyImplyLeading = true,
586
    this.automaticallyImplyTitle = true,
587
    this.alwaysShowMiddle = true,
588
    this.previousPageTitle,
589 590
    this.middle,
    this.trailing,
591
    this.border = _kDefaultNavBarBorder,
xster's avatar
xster committed
592
    this.backgroundColor,
593
    this.brightness,
594
    this.padding,
595 596
    this.transitionBetweenRoutes = true,
    this.heroTag = _defaultHeroTag,
597
    this.stretch = false,
598
  }) : assert(
599
         automaticallyImplyTitle || largeTitle != null,
600 601
         'No largeTitle has been provided but automaticallyImplyTitle is also '
         'false. Either provide a largeTitle or set automaticallyImplyTitle to '
602
         'true.',
603
       );
604 605 606 607

  /// The navigation bar's title.
  ///
  /// This text will appear in the top static navigation bar when collapsed and
608 609 610 611 612 613 614 615 616 617 618
  /// 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).
619 620 621 622
  ///
  /// If null and [automaticallyImplyTitle] is true, an appropriate [Text]
  /// title will be created if the current route is a [CupertinoPageRoute] and
  /// has a `title`.
623 624 625
  ///
  /// This parameter must either be non-null or the route must have a title
  /// ([CupertinoPageRoute.title]) and [automaticallyImplyTitle] must be true.
626
  final Widget? largeTitle;
627

628
  /// {@macro flutter.cupertino.CupertinoNavigationBar.leading}
629 630
  ///
  /// This widget is visible in both collapsed and expanded states.
631
  final Widget? leading;
632

633
  /// {@macro flutter.cupertino.CupertinoNavigationBar.automaticallyImplyLeading}
634 635 636
  final bool automaticallyImplyLeading;

  /// Controls whether we should try to imply the [largeTitle] widget if null.
637
  ///
638 639 640
  /// 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.
641 642
  ///
  /// This value cannot be null.
643 644
  final bool automaticallyImplyTitle;

645 646 647 648 649 650 651 652 653 654 655
  /// Controls whether [middle] widget should always be visible (even in
  /// expanded state).
  ///
  /// If true (default) and [middle] is not null, [middle] widget is always
  /// visible. If false, [middle] widget is visible only in collapsed state if
  /// it is provided.
  ///
  /// This should be set to false if you only want to show [largeTitle] in
  /// expanded state and [middle] in collapsed state.
  final bool alwaysShowMiddle;

656
  /// {@macro flutter.cupertino.CupertinoNavigationBar.previousPageTitle}
657
  final String? previousPageTitle;
658

659 660
  /// A widget to place in the middle of the static navigation bar instead of
  /// the [largeTitle].
661
  ///
662 663
  /// This widget is visible in both collapsed and expanded states if
  /// [alwaysShowMiddle] is true, otherwise just in collapsed state. The text
664 665
  /// supplied in [largeTitle] will no longer appear in collapsed state if a
  /// [middle] widget is provided.
666
  final Widget? middle;
667

668
  /// {@macro flutter.cupertino.CupertinoNavigationBar.trailing}
669 670
  ///
  /// This widget is visible in both collapsed and expanded states.
671
  final Widget? trailing;
672

673
  /// {@macro flutter.cupertino.CupertinoNavigationBar.backgroundColor}
674
  final Color? backgroundColor;
675

676
  /// {@macro flutter.cupertino.CupertinoNavigationBar.brightness}
677
  final Brightness? brightness;
678

679
  /// {@macro flutter.cupertino.CupertinoNavigationBar.padding}
680
  final EdgeInsetsDirectional? padding;
681

682
  /// {@macro flutter.cupertino.CupertinoNavigationBar.border}
683
  final Border? border;
684

685
  /// {@macro flutter.cupertino.CupertinoNavigationBar.transitionBetweenRoutes}
686 687
  final bool transitionBetweenRoutes;

688
  /// {@macro flutter.cupertino.CupertinoNavigationBar.heroTag}
689 690
  final Object heroTag;

691
  /// True if the navigation bar's background color has no transparency.
692
  bool get opaque => backgroundColor?.alpha == 0xFF;
693

694 695 696 697
  /// Whether the nav bar should stretch to fill the over-scroll area.
  ///
  /// The nav bar can still expand and contract as the user scrolls, but it will
  /// also stretch when the user over-scrolls if the [stretch] value is `true`.
698 699 700 701 702 703
  ///
  /// When set to `true`, the nav bar will prevent subsequent slivers from
  /// accessing overscrolls. This may be undesirable for using overscroll-based
  /// widgets like the [CupertinoSliverRefreshControl].
  ///
  /// Defaults to `false`.
704 705
  final bool stretch;

706
  @override
707
  State<CupertinoSliverNavigationBar> createState() => _CupertinoSliverNavigationBarState();
708 709 710 711 712 713
}

// 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> {
714
  late _NavigationBarStaticComponentsKeys keys;
715 716 717 718

  @override
  void initState() {
    super.initState();
719
    keys = _NavigationBarStaticComponentsKeys();
720 721
  }

722 723
  @override
  Widget build(BuildContext context) {
724
    final _NavigationBarStaticComponents components = _NavigationBarStaticComponents(
725 726 727 728 729 730 731 732 733 734 735
      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,
736 737
    );

738
    return MediaQuery.withNoTextScaling(
739 740 741 742 743 744 745 746 747 748 749 750 751
      child: SliverPersistentHeader(
        pinned: true, // iOS navigation bars are always pinned.
        delegate: _LargeTitleNavigationBarSliverDelegate(
          keys: keys,
          components: components,
          userMiddle: widget.middle,
          backgroundColor: CupertinoDynamicColor.maybeResolve(widget.backgroundColor, context) ?? CupertinoTheme.of(context).barBackgroundColor,
          brightness: widget.brightness,
          border: widget.border,
          padding: widget.padding,
          actionsForegroundColor: CupertinoTheme.of(context).primaryColor,
          transitionBetweenRoutes: widget.transitionBetweenRoutes,
          heroTag: widget.heroTag,
752
          persistentHeight: _kNavBarPersistentHeight + MediaQuery.paddingOf(context).top,
753
          alwaysShowMiddle: widget.alwaysShowMiddle && widget.middle != null,
754
          stretchConfiguration: widget.stretch ? OverScrollHeaderStretchConfiguration() : null,
xster's avatar
xster committed
755
        ),
756 757
      ),
    );
758 759 760
  }
}

761
class _LargeTitleNavigationBarSliverDelegate
762
    extends SliverPersistentHeaderDelegate with DiagnosticableTreeMixin {
763
  _LargeTitleNavigationBarSliverDelegate({
764 765 766 767 768 769 770 771 772 773 774 775
    required this.keys,
    required this.components,
    required this.userMiddle,
    required this.backgroundColor,
    required this.brightness,
    required this.border,
    required this.padding,
    required this.actionsForegroundColor,
    required this.transitionBetweenRoutes,
    required this.heroTag,
    required this.persistentHeight,
    required this.alwaysShowMiddle,
776
    required this.stretchConfiguration,
777
  });
778 779 780

  final _NavigationBarStaticComponentsKeys keys;
  final _NavigationBarStaticComponents components;
781
  final Widget? userMiddle;
782
  final Color backgroundColor;
783 784 785
  final Brightness? brightness;
  final Border? border;
  final EdgeInsetsDirectional? padding;
786
  final Color actionsForegroundColor;
787 788 789 790
  final bool transitionBetweenRoutes;
  final Object heroTag;
  final double persistentHeight;
  final bool alwaysShowMiddle;
791 792 793 794 795 796 797

  @override
  double get minExtent => persistentHeight;

  @override
  double get maxExtent => persistentHeight + _kNavBarLargeTitleHeightExtension;

798 799 800
  @override
  OverScrollHeaderStretchConfiguration? stretchConfiguration;

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

805
    final _PersistentNavigationBar persistentNavigationBar =
806
        _PersistentNavigationBar(
807
      components: components,
808
      padding: padding,
809 810 811
      // If a user specified middle exists, always show it. Otherwise, show
      // title when sliver is collapsed.
      middleVisible: alwaysShowMiddle ? null : !showLargeTitle,
812 813
    );

814
    final Widget navBar = _wrapWithBackground(
815
      border: border,
816
      backgroundColor: CupertinoDynamicColor.resolve(backgroundColor, context),
817
      brightness: brightness,
xster's avatar
xster committed
818 819 820 821 822 823 824 825 826 827 828
      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(
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
                child: Padding(
                  padding: const EdgeInsetsDirectional.only(
                    start: _kNavBarEdgePadding,
                    bottom: _kNavBarBottomPadding
                  ),
                  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: _LargeTitle(
                            child: components.largeTitle,
xster's avatar
xster committed
850
                          ),
851 852 853 854 855 856 857
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
xster's avatar
xster committed
858 859 860 861 862 863 864 865
            Positioned(
              left: 0.0,
              right: 0.0,
              top: 0.0,
              child: persistentNavigationBar,
            ),
          ],
        ),
866 867
      ),
    );
868 869 870 871 872

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

873
    return Hero(
874 875 876
      tag: heroTag == _defaultHeroTag
          ? _HeroTag(Navigator.of(context))
          : heroTag,
877 878 879
      createRectTween: _linearTranslateWithLargestRectSizeTween,
      flightShuttleBuilder: _navBarHeroFlightShuttleBuilder,
      placeholderBuilder: _navBarHeroLaunchPadBuilder,
xster's avatar
xster committed
880
      transitionOnUserGestures: true,
881 882 883
      // 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.
884
      child: _TransitionableNavigationBar(
885
        componentsKeys: keys,
886
        backgroundColor: CupertinoDynamicColor.resolve(backgroundColor, context),
xster's avatar
xster committed
887 888 889
        backButtonTextStyle: CupertinoTheme.of(context).textTheme.navActionTextStyle,
        titleTextStyle: CupertinoTheme.of(context).textTheme.navTitleTextStyle,
        largeTitleTextStyle: CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle,
890
        border: border,
891
        hasUserMiddle: userMiddle != null && (alwaysShowMiddle || !showLargeTitle),
892 893 894 895
        largeExpanded: showLargeTitle,
        child: navBar,
      ),
    );
896 897 898
  }

  @override
899
  bool shouldRebuild(_LargeTitleNavigationBarSliverDelegate oldDelegate) {
900
    return components != oldDelegate.components
901
        || userMiddle != oldDelegate.userMiddle
902
        || backgroundColor != oldDelegate.backgroundColor
903 904 905 906 907 908 909
        || border != oldDelegate.border
        || padding != oldDelegate.padding
        || actionsForegroundColor != oldDelegate.actionsForegroundColor
        || transitionBetweenRoutes != oldDelegate.transitionBetweenRoutes
        || persistentHeight != oldDelegate.persistentHeight
        || alwaysShowMiddle != oldDelegate.alwaysShowMiddle
        || heroTag != oldDelegate.heroTag;
910 911 912
  }
}

913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
/// The large title of the navigation bar.
///
/// Magnifies on over-scroll when [CupertinoSliverNavigationBar.stretch]
/// parameter is true.
class _LargeTitle extends SingleChildRenderObjectWidget {
  const _LargeTitle({ super.child });

  @override
  _RenderLargeTitle createRenderObject(BuildContext context) {
    return _RenderLargeTitle(alignment: AlignmentDirectional.bottomStart.resolve(Directionality.of(context)));
  }

  @override
  void updateRenderObject(BuildContext context, _RenderLargeTitle renderObject) {
    renderObject.alignment = AlignmentDirectional.bottomStart.resolve(Directionality.of(context));
  }
}

class _RenderLargeTitle extends RenderShiftedBox {
  _RenderLargeTitle({
    required Alignment alignment,
  })  : _alignment = alignment,
        super(null);

  Alignment get alignment => _alignment;
  Alignment _alignment;
  set alignment(Alignment value) {
    if (_alignment == value) {
      return;
    }
    _alignment = value;

    markNeedsLayout();
  }

  double _scale = 1.0;

  @override
  void performLayout() {
    final RenderBox? child = this.child;
    Size childSize = Size.zero;

    size = constraints.biggest;

    if (child == null) {
      return;
    }

Lioness100's avatar
Lioness100 committed
961 962
    final BoxConstraints childConstraints = constraints.widthConstraints().loosen();
    child.layout(childConstraints, parentUsesSize: true);
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

    final double maxScale = child.size.width != 0.0
      ? clampDouble(constraints.maxWidth / child.size.width, 1.0, 1.1)
      : 1.1;
    _scale = clampDouble(
      1.0 + (constraints.maxHeight - (_kNavBarLargeTitleHeightExtension - _kNavBarBottomPadding)) / (_kNavBarLargeTitleHeightExtension - _kNavBarBottomPadding) * 0.03,
      1.0,
      maxScale,
    );

    childSize = child.size * _scale;
    final BoxParentData childParentData = child.parentData! as BoxParentData;
    childParentData.offset = alignment.alongOffset(size - childSize as Offset);
  }

  @override
  void applyPaintTransform(RenderBox child, Matrix4 transform) {
    assert(child == this.child);

    super.applyPaintTransform(child, transform);

    transform.scale(_scale, _scale);
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    final RenderBox? child = this.child;

    if (child == null) {
      layer = null;
    } else {
      final BoxParentData childParentData = child.parentData! as BoxParentData;

      layer = context.pushTransform(
        needsCompositing,
        offset + childParentData.offset,
        Matrix4.diagonal3Values(_scale, _scale, 1.0),
        (PaintingContext context, Offset offset) => context.paintChild(child, offset),
        oldLayer: layer as TransformLayer?,
      );
    }
  }

  @override
  bool hitTestChildren(BoxHitTestResult result, {required Offset position}) {
    final RenderBox? child = this.child;

    if (child == null) {
      return false;
    }

    final Offset childOffset = (child.parentData! as BoxParentData).offset;

    final Matrix4 transform = Matrix4.identity()
      ..scale(1.0/_scale, 1.0/_scale, 1.0)
      ..translate(-childOffset.dx, -childOffset.dy);

    return result.addWithRawTransform(
      transform: transform,
      position: position,
      hitTest: (BoxHitTestResult result, Offset transformed) {
        return child.hitTest(result, position: transformed);
      }
    );
  }
}

1030
/// The top part of the navigation bar that's never scrolled away.
1031
///
1032
/// Consists of the entire navigation bar without background and border when used
1033 1034
/// without large titles. With large titles, it's the top static half that
/// doesn't scroll.
1035 1036
class _PersistentNavigationBar extends StatelessWidget {
  const _PersistentNavigationBar({
1037
    required this.components,
1038
    this.padding,
1039
    this.middleVisible,
1040
  });
1041

1042
  final _NavigationBarStaticComponents components;
1043

1044
  final EdgeInsetsDirectional? padding;
1045 1046
  /// Whether the middle widget has a visible animated opacity. A null value
  /// means the middle opacity will not be animated.
1047
  final bool? middleVisible;
1048

1049 1050
  @override
  Widget build(BuildContext context) {
1051
    Widget? middle = components.middle;
1052

1053
    if (middle != null) {
1054
      middle = DefaultTextStyle(
xster's avatar
xster committed
1055
        style: CupertinoTheme.of(context).textTheme.navTitleTextStyle,
1056
        child: Semantics(header: true, child: middle),
1057 1058 1059 1060 1061
      );
      // When the middle's visibility can change on the fly like with large title
      // slivers, wrap with animated opacity.
      middle = middleVisible == null
        ? middle
1062
        : AnimatedOpacity(
1063
          opacity: middleVisible! ? 1.0 : 0.0,
1064 1065
          duration: _kNavBarTitleFadeDuration,
          child: middle,
1066
        );
1067
    }
1068

1069 1070 1071
    Widget? leading = components.leading;
    final Widget? backChevron = components.backChevron;
    final Widget? backLabel = components.backLabel;
1072

1073
    if (leading == null && backChevron != null && backLabel != null) {
1074
      leading = CupertinoNavigationBarBackButton._assemble(
1075 1076
        backChevron,
        backLabel,
1077
      );
1078
    }
1079

1080
    Widget paddedToolbar = NavigationToolbar(
1081 1082 1083
      leading: leading,
      middle: middle,
      trailing: components.trailing,
1084
      middleSpacing: 6.0,
1085 1086 1087
    );

    if (padding != null) {
1088
      paddedToolbar = Padding(
1089
        padding: EdgeInsets.only(
1090 1091
          top: padding!.top,
          bottom: padding!.bottom,
1092 1093 1094 1095 1096
        ),
        child: paddedToolbar,
      );
    }

1097
    return SizedBox(
1098
      height: _kNavBarPersistentHeight + MediaQuery.paddingOf(context).top,
1099
      child: SafeArea(
1100 1101
        bottom: false,
        child: paddedToolbar,
1102 1103
      ),
    );
1104 1105
  }
}
1106

1107 1108 1109 1110 1111 1112 1113 1114 1115
// 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()
1116 1117 1118 1119 1120 1121 1122
    : 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');
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139

  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({
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
    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,
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
  }) : 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,
       );

1192 1193 1194
  static Widget? _derivedTitle({
    required bool automaticallyImplyTitle,
    ModalRoute<dynamic>? currentRoute,
1195 1196 1197
  }) {
    // Auto use the CupertinoPageRoute's title if middle not provided.
    if (automaticallyImplyTitle &&
1198
        currentRoute is CupertinoRouteTransitionMixin &&
1199
        currentRoute.title != null) {
1200
      return Text(currentRoute.title!);
1201 1202 1203 1204 1205
    }

    return null;
  }

1206 1207 1208 1209 1210 1211 1212
  final KeyedSubtree? leading;
  static KeyedSubtree? createLeading({
    required GlobalKey leadingKey,
    required Widget? userLeading,
    required ModalRoute<dynamic>? route,
    required bool automaticallyImplyLeading,
    required EdgeInsetsDirectional? padding,
1213
  }) {
1214
    Widget? leadingContent;
1215 1216 1217 1218 1219 1220 1221 1222 1223

    if (userLeading != null) {
      leadingContent = userLeading;
    } else if (
      automaticallyImplyLeading &&
      route is PageRoute &&
      route.canPop &&
      route.fullscreenDialog
    ) {
1224
      leadingContent = CupertinoButton(
1225
        padding: EdgeInsets.zero,
1226
        onPressed: () { route.navigator!.maybePop(); },
1227
        child: const Text('Close'),
1228 1229 1230 1231 1232 1233 1234
      );
    }

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

1235
    return KeyedSubtree(
1236
      key: leadingKey,
1237 1238
      child: Padding(
        padding: EdgeInsetsDirectional.only(
1239 1240
          start: padding?.start ?? _kNavBarEdgePadding,
        ),
xster's avatar
xster committed
1241 1242 1243
        child: IconTheme.merge(
          data: const IconThemeData(
            size: 32.0,
1244
          ),
xster's avatar
xster committed
1245
          child: leadingContent,
1246 1247 1248 1249 1250
        ),
      ),
    );
  }

1251 1252 1253 1254 1255 1256
  final KeyedSubtree? backChevron;
  static KeyedSubtree? createBackChevron({
    required GlobalKey backChevronKey,
    required Widget? userLeading,
    required ModalRoute<dynamic>? route,
    required bool automaticallyImplyLeading,
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
  }) {
    if (
      userLeading != null ||
      !automaticallyImplyLeading ||
      route == null ||
      !route.canPop ||
      (route is PageRoute && route.fullscreenDialog)
    ) {
      return null;
    }

1268
    return KeyedSubtree(key: backChevronKey, child: const _BackChevron());
1269 1270 1271 1272
  }

  /// This widget is not decorated with a font since the font style could
  /// animate during transitions.
1273 1274 1275 1276 1277 1278 1279
  final KeyedSubtree? backLabel;
  static KeyedSubtree? createBackLabel({
    required GlobalKey backLabelKey,
    required Widget? userLeading,
    required ModalRoute<dynamic>? route,
    required bool automaticallyImplyLeading,
    required String? previousPageTitle,
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
  }) {
    if (
      userLeading != null ||
      !automaticallyImplyLeading ||
      route == null ||
      !route.canPop ||
      (route is PageRoute && route.fullscreenDialog)
    ) {
      return null;
    }

1291
    return KeyedSubtree(
1292
      key: backLabelKey,
1293
      child: _BackLabel(
1294 1295 1296 1297 1298 1299 1300 1301
        specifiedPreviousTitle: previousPageTitle,
        route: route,
      ),
    );
  }

  /// This widget is not decorated with a font since the font style could
  /// animate during transitions.
1302 1303 1304 1305 1306 1307 1308 1309
  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,
1310
  }) {
1311
    Widget? middleContent = userMiddle;
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325

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

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

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

1326
    return KeyedSubtree(
1327 1328 1329 1330 1331
      key: middleKey,
      child: middleContent,
    );
  }

1332 1333 1334 1335 1336
  final KeyedSubtree? trailing;
  static KeyedSubtree? createTrailing({
    required GlobalKey trailingKey,
    required Widget? userTrailing,
    required EdgeInsetsDirectional? padding,
1337 1338 1339 1340 1341
  }) {
    if (userTrailing == null) {
      return null;
    }

1342
    return KeyedSubtree(
1343
      key: trailingKey,
1344 1345
      child: Padding(
        padding: EdgeInsetsDirectional.only(
1346 1347
          end: padding?.end ?? _kNavBarEdgePadding,
        ),
xster's avatar
xster committed
1348 1349 1350
        child: IconTheme.merge(
          data: const IconThemeData(
            size: 32.0,
1351
          ),
xster's avatar
xster committed
1352
          child: userTrailing,
1353 1354 1355 1356 1357 1358 1359
        ),
      ),
    );
  }

  /// This widget is not decorated with a font since the font style could
  /// animate during transitions.
1360 1361 1362 1363 1364 1365 1366
  final KeyedSubtree? largeTitle;
  static KeyedSubtree? createLargeTitle({
    required GlobalKey largeTitleKey,
    required Widget? userLargeTitle,
    required bool large,
    required bool automaticImplyTitle,
    required ModalRoute<dynamic>? route,
1367 1368 1369 1370 1371
  }) {
    if (!large) {
      return null;
    }

1372
    final Widget? largeTitleContent = userLargeTitle ?? _derivedTitle(
1373 1374 1375 1376 1377 1378 1379 1380 1381
      automaticallyImplyTitle: automaticImplyTitle,
      currentRoute: route,
    );

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

1382
    return KeyedSubtree(
1383
      key: largeTitleKey,
1384
      child: largeTitleContent!,
1385 1386 1387 1388
    );
  }
}

1389 1390 1391 1392 1393 1394
/// A nav bar back button typically used in [CupertinoNavigationBar].
///
/// This is automatically inserted into [CupertinoNavigationBar] and
/// [CupertinoSliverNavigationBar]'s `leading` slot when
/// `automaticallyImplyLeading` is true.
///
1395 1396 1397 1398
/// When manually inserted, the [CupertinoNavigationBarBackButton] should only
/// be used in routes that can be popped unless a custom [onPressed] is
/// provided.
///
1399 1400 1401 1402 1403 1404 1405 1406 1407
/// 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({
1408
    super.key,
xster's avatar
xster committed
1409
    this.color,
1410
    this.previousPageTitle,
1411
    this.onPressed,
1412
  }) : _backChevron = null,
1413
       _backLabel = null;
1414 1415 1416 1417 1418 1419 1420

  // 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,
1421 1422
      color = null,
      onPressed = null;
1423 1424

  /// The [Color] of the back button.
1425
  ///
xster's avatar
xster committed
1426 1427 1428
  /// Can be used to override the color of the back button chevron and label.
  ///
  /// Defaults to [CupertinoTheme]'s `primaryColor` if null.
1429
  final Color? color;
1430

1431 1432 1433
  /// 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.
1434
  final String? previousPageTitle;
1435

1436 1437 1438 1439
  /// 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
1440 1441
  /// via [SystemNavigator] instead of Flutter's [Navigator] in add-to-app
  /// situations.
1442 1443
  ///
  /// Defaults to null.
1444
  final VoidCallback? onPressed;
1445

1446
  final Widget? _backChevron;
1447

1448
  final Widget? _backLabel;
1449

1450 1451
  @override
  Widget build(BuildContext context) {
1452
    final ModalRoute<dynamic>? currentRoute = ModalRoute.of(context);
1453 1454
    if (onPressed == null) {
      assert(
1455
        currentRoute?.canPop ?? false,
1456 1457 1458
        'CupertinoNavigationBarBackButton should only be used in routes that can be popped',
      );
    }
1459

xster's avatar
xster committed
1460 1461
    TextStyle actionTextStyle = CupertinoTheme.of(context).textTheme.navActionTextStyle;
    if (color != null) {
1462
      actionTextStyle = actionTextStyle.copyWith(color: CupertinoDynamicColor.maybeResolve(color, context));
xster's avatar
xster committed
1463 1464
    }

1465
    return CupertinoButton(
1466
      padding: EdgeInsets.zero,
1467
      child: Semantics(
1468 1469 1470 1471
        container: true,
        excludeSemantics: true,
        label: 'Back',
        button: true,
xster's avatar
xster committed
1472 1473 1474 1475
        child: DefaultTextStyle(
          style: actionTextStyle,
          child: ConstrainedBox(
            constraints: const BoxConstraints(minWidth: _kNavBarBackButtonTapWidth),
1476
            child: Row(
1477 1478 1479 1480 1481
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                const Padding(padding: EdgeInsetsDirectional.only(start: 8.0)),
                _backChevron ?? const _BackChevron(),
                const Padding(padding: EdgeInsetsDirectional.only(start: 6.0)),
1482 1483
                Flexible(
                  child: _backLabel ?? _BackLabel(
1484 1485 1486
                    specifiedPreviousTitle: previousPageTitle,
                    route: currentRoute,
                  ),
1487
                ),
1488 1489
              ],
            ),
1490 1491 1492
          ),
        ),
      ),
1493 1494
      onPressed: () {
        if (onPressed != null) {
1495
          onPressed!();
1496 1497 1498 1499
        } else {
          Navigator.maybePop(context);
        }
      },
1500 1501 1502
    );
  }
}
1503

1504

1505
class _BackChevron extends StatelessWidget {
1506
  const _BackChevron();
1507 1508

  @override
1509
  Widget build(BuildContext context) {
1510
    final TextDirection textDirection = Directionality.of(context);
1511
    final TextStyle textStyle = DefaultTextStyle.of(context).style;
1512 1513 1514

    // Replicate the Icon logic here to get a tightly sized icon and add
    // custom non-square padding.
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
    Widget iconWidget = Padding(
      padding: const EdgeInsetsDirectional.only(start: 6, end: 2),
      child: Text.rich(
        TextSpan(
          text: String.fromCharCode(CupertinoIcons.back.codePoint),
          style: TextStyle(
            inherit: false,
            color: textStyle.color,
            fontSize: 30.0,
            fontFamily: CupertinoIcons.back.fontFamily,
            package: CupertinoIcons.back.fontPackage,
          ),
1527 1528 1529 1530 1531
        ),
      ),
    );
    switch (textDirection) {
      case TextDirection.rtl:
1532 1533
        iconWidget = Transform(
          transform: Matrix4.identity()..scale(-1.0, 1.0, 1.0),
1534 1535 1536 1537 1538 1539 1540
          alignment: Alignment.center,
          transformHitTests: false,
          child: iconWidget,
        );
      case TextDirection.ltr:
        break;
    }
1541

1542 1543 1544
    return iconWidget;
  }
}
1545

1546 1547 1548 1549
/// A widget that shows next to the back chevron when `automaticallyImplyLeading`
/// is true.
class _BackLabel extends StatelessWidget {
  const _BackLabel({
1550 1551
    required this.specifiedPreviousTitle,
    required this.route,
1552
  });
1553

1554 1555
  final String? specifiedPreviousTitle;
  final ModalRoute<dynamic>? route;
1556 1557 1558

  // `child` is never passed in into ValueListenableBuilder so it's always
  // null here and unused.
1559
  Widget _buildPreviousTitleWidget(BuildContext context, String? previousTitle, Widget? child) {
1560
    if (previousTitle == null) {
1561
      return const SizedBox.shrink();
1562
    }
1563

1564
    Text textWidget = Text(
1565 1566 1567 1568 1569 1570 1571
      previousTitle,
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );

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

1574
    return Align(
1575 1576 1577 1578
      alignment: AlignmentDirectional.centerStart,
      widthFactor: 1.0,
      child: textWidget,
    );
1579 1580 1581
  }

  @override
1582 1583 1584
  Widget build(BuildContext context) {
    if (specifiedPreviousTitle != null) {
      return _buildPreviousTitleWidget(context, specifiedPreviousTitle, null);
1585
    } else if (route is CupertinoRouteTransitionMixin<dynamic> && !route!.isFirst) {
1586
      final CupertinoRouteTransitionMixin<dynamic> cupertinoRoute = route! as CupertinoRouteTransitionMixin<dynamic>;
1587 1588 1589
      // There is no timing issue because the previousTitle Listenable changes
      // happen during route modifications before the ValueListenableBuilder
      // is built.
1590
      return ValueListenableBuilder<String?>(
1591 1592 1593 1594
        valueListenable: cupertinoRoute.previousTitle,
        builder: _buildPreviousTitleWidget,
      );
    } else {
1595
      return const SizedBox.shrink();
1596
    }
1597 1598
  }
}
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609

/// 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({
1610 1611 1612 1613 1614 1615 1616 1617 1618
    required this.componentsKeys,
    required this.backgroundColor,
    required this.backButtonTextStyle,
    required this.titleTextStyle,
    required this.largeTitleTextStyle,
    required this.border,
    required this.hasUserMiddle,
    required this.largeExpanded,
    required this.child,
1619
  }) : assert(!largeExpanded || largeTitleTextStyle != null),
1620 1621 1622
       super(key: componentsKeys.navBarBoxKey);

  final _NavigationBarStaticComponentsKeys componentsKeys;
1623
  final Color? backgroundColor;
xster's avatar
xster committed
1624 1625
  final TextStyle backButtonTextStyle;
  final TextStyle titleTextStyle;
1626 1627
  final TextStyle? largeTitleTextStyle;
  final Border? border;
1628 1629 1630 1631 1632
  final bool hasUserMiddle;
  final bool largeExpanded;
  final Widget child;

  RenderBox get renderBox {
1633
    final RenderBox box = componentsKeys.navBarBoxKey.currentContext!.findRenderObject()! as RenderBox;
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
    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(() {
1646
      bool inHero = false;
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
      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;
          }
        }
        return true;
      });
      assert(
1663
        inHero,
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
        '_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({
1690 1691 1692
    required this.animation,
    required this.topNavBar,
    required this.bottomNavBar,
1693
  }) : heightTween = Tween<double>(
1694 1695 1696
         begin: bottomNavBar.renderBox.size.height,
         end: topNavBar.renderBox.size.height,
       ),
1697
       backgroundTween = ColorTween(
1698 1699 1700
         begin: bottomNavBar.backgroundColor,
         end: topNavBar.backgroundColor,
       ),
1701
       borderTween = BorderTween(
1702 1703 1704 1705 1706
         begin: bottomNavBar.border,
         end: topNavBar.border,
       );

  final Animation<double> animation;
1707 1708
  final _TransitionableNavigationBar topNavBar;
  final _TransitionableNavigationBar bottomNavBar;
1709 1710 1711 1712 1713 1714 1715

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

  @override
  Widget build(BuildContext context) {
1716 1717 1718 1719
    final _NavigationBarComponentsTransition componentsTransition = _NavigationBarComponentsTransition(
      animation: animation,
      bottomNavBar: bottomNavBar,
      topNavBar: topNavBar,
1720
      directionality: Directionality.of(context),
1721 1722
    );

1723 1724 1725 1726 1727
    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,
1728
        builder: (BuildContext context, Widget? child) {
1729 1730 1731
          return _wrapWithBackground(
            // Don't update the system status bar color mid-flight.
            updateSystemUiOverlay: false,
1732
            backgroundColor: backgroundTween.evaluate(animation)!,
1733
            border: borderTween.evaluate(animation),
1734
            child: SizedBox(
1735 1736 1737 1738 1739 1740 1741
              height: heightTween.evaluate(animation),
              width: double.infinity,
            ),
          );
        },
      ),
      // Draw all the components on top of the empty bar box.
1742 1743 1744 1745 1746 1747
      if (componentsTransition.bottomBackChevron != null) componentsTransition.bottomBackChevron!,
      if (componentsTransition.bottomBackLabel != null) componentsTransition.bottomBackLabel!,
      if (componentsTransition.bottomLeading != null) componentsTransition.bottomLeading!,
      if (componentsTransition.bottomMiddle != null) componentsTransition.bottomMiddle!,
      if (componentsTransition.bottomLargeTitle != null) componentsTransition.bottomLargeTitle!,
      if (componentsTransition.bottomTrailing != null) componentsTransition.bottomTrailing!,
1748
      // Draw top components on top of the bottom components.
1749 1750 1751 1752 1753 1754
      if (componentsTransition.topLeading != null) componentsTransition.topLeading!,
      if (componentsTransition.topBackChevron != null) componentsTransition.topBackChevron!,
      if (componentsTransition.topBackLabel != null) componentsTransition.topBackLabel!,
      if (componentsTransition.topMiddle != null) componentsTransition.topMiddle!,
      if (componentsTransition.topLargeTitle != null) componentsTransition.topLargeTitle!,
      if (componentsTransition.topTrailing != null) componentsTransition.topTrailing!,
1755 1756 1757 1758 1759 1760
    ];


    // 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
1761 1762 1763
    // the animation, such as the topLargeTitle. The text scaling is disabled to
    // avoid odd transitions between pages.
    return MediaQuery.withNoTextScaling(
1764 1765 1766 1767 1768 1769
      child: SizedBox(
        height: math.max(heightTween.begin!, heightTween.end!) + MediaQuery.paddingOf(context).top,
        width: double.infinity,
        child: Stack(
          children: children,
        ),
1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
      ),
    );
  }
}

/// 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({
1799 1800 1801 1802
    required this.animation,
    required _TransitionableNavigationBar bottomNavBar,
    required _TransitionableNavigationBar topNavBar,
    required TextDirection directionality,
1803 1804 1805 1806
  }) : bottomComponents = bottomNavBar.componentsKeys,
       topComponents = topNavBar.componentsKeys,
       bottomNavBarBox = bottomNavBar.renderBox,
       topNavBarBox = topNavBar.renderBox,
xster's avatar
xster committed
1807 1808 1809 1810 1811 1812
       bottomBackButtonTextStyle = bottomNavBar.backButtonTextStyle,
       topBackButtonTextStyle = topNavBar.backButtonTextStyle,
       bottomTitleTextStyle = bottomNavBar.titleTextStyle,
       topTitleTextStyle = topNavBar.titleTextStyle,
       bottomLargeTitleTextStyle = bottomNavBar.largeTitleTextStyle,
       topLargeTitleTextStyle = topNavBar.largeTitleTextStyle,
1813 1814 1815 1816 1817 1818
       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.
1819 1820
           bottomNavBar.renderBox.paintBounds.expandToInclude(topNavBar.renderBox.paintBounds),
       forwardDirection = directionality == TextDirection.ltr ? 1.0 : -1.0;
1821

1822
  static final Animatable<double> fadeOut = Tween<double>(
1823 1824 1825
    begin: 1.0,
    end: 0.0,
  );
1826
  static final Animatable<double> fadeIn = Tween<double>(
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
    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
1841 1842 1843 1844
  final TextStyle bottomBackButtonTextStyle;
  final TextStyle topBackButtonTextStyle;
  final TextStyle bottomTitleTextStyle;
  final TextStyle topTitleTextStyle;
1845 1846
  final TextStyle? bottomLargeTitleTextStyle;
  final TextStyle? topLargeTitleTextStyle;
xster's avatar
xster committed
1847

1848 1849 1850 1851 1852 1853 1854 1855 1856
  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;

1857 1858 1859
  // x-axis unity number representing the direction of growth for text.
  final double forwardDirection;

1860 1861 1862 1863
  // 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, {
1864
    required RenderBox from,
1865
  }) {
1866
    final RenderBox componentBox = key.currentContext!.findRenderObject()! as RenderBox;
1867 1868
    assert(componentBox.attached);

1869
    return RelativeRect.fromRect(
1870 1871 1872 1873 1874
      componentBox.localToGlobal(Offset.zero, ancestor: from) & componentBox.size,
      transitionBox,
    );
  }

1875 1876 1877
  // Create an animated widget that moves the given child widget between its
  // original position in its ancestor navigation bar to another widget's
  // position in that widget's navigation bar.
1878
  //
1879 1880
  // Anchor their positions based on the vertical middle of their respective
  // render boxes' leading edge.
1881
  //
1882 1883 1884 1885 1886 1887 1888
  // This method assumes there's no other transforms other than translations
  // when converting a rect from the original navigation bar's coordinate space
  // to the other navigation bar's coordinate space, to avoid performing
  // floating point operations on the size of the child widget, so that the
  // incoming constraints used for sizing the child widget will be exactly the
  // same.
  _FixedSizeSlidingTransition slideFromLeadingEdge({
1889 1890 1891 1892
    required GlobalKey fromKey,
    required RenderBox fromNavBarBox,
    required GlobalKey toKey,
    required RenderBox toNavBarBox,
1893
    required Widget child,
1894
  }) {
1895 1896
    final RenderBox fromBox = fromKey.currentContext!.findRenderObject()! as RenderBox;
    final RenderBox toBox = toKey.currentContext!.findRenderObject()! as RenderBox;
1897

1898
    final bool isLTR = forwardDirection > 0;
1899

1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930
    // The animation moves the fromBox so its anchor (left-center or right-center
    // depending on the writing direction) aligns with toBox's anchor.
    final Offset fromAnchorLocal = Offset(
      isLTR ? 0 : fromBox.size.width,
      fromBox.size.height / 2,
    );
    final Offset toAnchorLocal = Offset(
      isLTR ? 0 : toBox.size.width,
      toBox.size.height / 2,
    );
    final Offset fromAnchorInFromBox = fromBox.localToGlobal(fromAnchorLocal, ancestor: fromNavBarBox);
    final Offset toAnchorInToBox = toBox.localToGlobal(toAnchorLocal, ancestor: toNavBarBox);

    // We can't get ahold of the render box of the stack (i.e., `transitionBox`)
    // we place components on yet, but we know the stack needs to be top-leading
    // aligned with both fromNavBarBox and toNavBarBox to make the transition
    // look smooth. Also use the top-leading point as the origin for ease of
    // calculation.

    // The offset to move fromAnchor to toAnchor, in transitionBox's top-leading
    // coordinates.
    final Offset translation = isLTR
      ? toAnchorInToBox - fromAnchorInFromBox
      : Offset(toNavBarBox.size.width - toAnchorInToBox.dx, toAnchorInToBox.dy)
      - Offset(fromNavBarBox.size.width - fromAnchorInFromBox.dx, fromAnchorInFromBox.dy);

    final RelativeRect fromBoxMargin = positionInTransitionBox(fromKey, from: fromNavBarBox);
    final Offset fromOriginInTransitionBox = Offset(
      isLTR ? fromBoxMargin.left : fromBoxMargin.right,
      fromBoxMargin.top,
    );
1931

1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942
    final Tween<Offset> anchorMovementInTransitionBox = Tween<Offset>(
      begin: fromOriginInTransitionBox,
      end: fromOriginInTransitionBox + translation,
    );

    return _FixedSizeSlidingTransition(
      isLTR: isLTR,
      offsetAnimation: animation.drive(anchorMovementInTransitionBox),
      size: fromBox.size,
      child: child,
    );
1943 1944 1945
  }

  Animation<double> fadeInFrom(double t, { Curve curve = Curves.easeIn }) {
1946 1947 1948
    return animation.drive(fadeIn.chain(
      CurveTween(curve: Interval(t, 1.0, curve: curve)),
    ));
1949 1950 1951
  }

  Animation<double> fadeOutBy(double t, { Curve curve = Curves.easeOut }) {
1952 1953 1954
    return animation.drive(fadeOut.chain(
      CurveTween(curve: Interval(0.0, t, curve: curve)),
    ));
1955 1956
  }

1957 1958
  Widget? get bottomLeading {
    final KeyedSubtree? bottomLeading = bottomComponents.leadingKey.currentWidget as KeyedSubtree?;
1959 1960 1961 1962 1963

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

1964
    return Positioned.fromRelativeRect(
1965
      rect: positionInTransitionBox(bottomComponents.leadingKey, from: bottomNavBarBox),
1966
      child: FadeTransition(
1967 1968 1969 1970 1971 1972
        opacity: fadeOutBy(0.4),
        child: bottomLeading.child,
      ),
    );
  }

1973 1974
  Widget? get bottomBackChevron {
    final KeyedSubtree? bottomBackChevron = bottomComponents.backChevronKey.currentWidget as KeyedSubtree?;
1975 1976 1977 1978 1979

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

1980
    return Positioned.fromRelativeRect(
1981
      rect: positionInTransitionBox(bottomComponents.backChevronKey, from: bottomNavBarBox),
1982
      child: FadeTransition(
1983
        opacity: fadeOutBy(0.6),
1984
        child: DefaultTextStyle(
xster's avatar
xster committed
1985
          style: bottomBackButtonTextStyle,
1986 1987 1988 1989 1990 1991
          child: bottomBackChevron.child,
        ),
      ),
    );
  }

1992 1993
  Widget? get bottomBackLabel {
    final KeyedSubtree? bottomBackLabel = bottomComponents.backLabelKey.currentWidget as KeyedSubtree?;
1994 1995 1996 1997 1998 1999 2000

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

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

2001
    // Transition away by sliding horizontally to the leading edge off of the screen.
2002
    final RelativeRectTween positionTween = RelativeRectTween(
2003
      begin: from,
2004 2005 2006 2007 2008 2009
      end: from.shift(
        Offset(
          forwardDirection * (-bottomNavBarBox.size.width / 2.0),
          0.0,
        ),
      ),
2010 2011
    );

2012
    return PositionedTransition(
2013
      rect: animation.drive(positionTween),
2014
      child: FadeTransition(
2015
        opacity: fadeOutBy(0.2),
2016
        child: DefaultTextStyle(
xster's avatar
xster committed
2017
          style: bottomBackButtonTextStyle,
2018 2019 2020 2021 2022 2023
          child: bottomBackLabel.child,
        ),
      ),
    );
  }

2024 2025 2026 2027
  Widget? get bottomMiddle {
    final KeyedSubtree? bottomMiddle = bottomComponents.middleKey.currentWidget as KeyedSubtree?;
    final KeyedSubtree? topBackLabel = topComponents.backLabelKey.currentWidget as KeyedSubtree?;
    final KeyedSubtree? topLeading = topComponents.leadingKey.currentWidget as KeyedSubtree?;
2028 2029 2030 2031 2032 2033 2034 2035

    // 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) {
2036
      // Move from current position to the top page's back label position.
2037 2038 2039 2040 2041
      return slideFromLeadingEdge(
        fromKey: bottomComponents.middleKey,
        fromNavBarBox: bottomNavBarBox,
        toKey: topComponents.backLabelKey,
        toNavBarBox: topNavBarBox,
2042
        child: FadeTransition(
2043 2044
          // A custom middle widget like a segmented control fades away faster.
          opacity: fadeOutBy(bottomHasUserMiddle ? 0.4 : 0.7),
2045
          child: Align(
2046 2047 2048
            // As the text shrinks, make sure it's still anchored to the leading
            // edge of a constantly sized outer box.
            alignment: AlignmentDirectional.centerStart,
2049
            child: DefaultTextStyleTransition(
2050
              style: animation.drive(TextStyleTween(
xster's avatar
xster committed
2051 2052
                begin: bottomTitleTextStyle,
                end: topBackButtonTextStyle,
2053
              )),
2054 2055 2056 2057 2058 2059 2060
              child: bottomMiddle.child,
            ),
          ),
        ),
      );
    }

2061 2062 2063
    // 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.
2064
    if (bottomMiddle != null && topLeading != null) {
2065
      return Positioned.fromRelativeRect(
2066
        rect: positionInTransitionBox(bottomComponents.middleKey, from: bottomNavBarBox),
2067
        child: FadeTransition(
2068 2069
          opacity: fadeOutBy(bottomHasUserMiddle ? 0.4 : 0.7),
          // Keep the font when transitioning into a non-back label leading.
2070
          child: DefaultTextStyle(
xster's avatar
xster committed
2071
            style: bottomTitleTextStyle,
2072 2073 2074 2075 2076 2077 2078 2079 2080
            child: bottomMiddle.child,
          ),
        ),
      );
    }

    return null;
  }

2081 2082 2083 2084
  Widget? get bottomLargeTitle {
    final KeyedSubtree? bottomLargeTitle = bottomComponents.largeTitleKey.currentWidget as KeyedSubtree?;
    final KeyedSubtree? topBackLabel = topComponents.backLabelKey.currentWidget as KeyedSubtree?;
    final KeyedSubtree? topLeading = topComponents.leadingKey.currentWidget as KeyedSubtree?;
2085 2086 2087 2088 2089

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

2090
    if (topBackLabel != null) {
2091
      // Move from current position to the top page's back label position.
2092 2093 2094 2095 2096
      return slideFromLeadingEdge(
        fromKey: bottomComponents.largeTitleKey,
        fromNavBarBox: bottomNavBarBox,
        toKey: topComponents.backLabelKey,
        toNavBarBox: topNavBarBox,
2097
        child: FadeTransition(
2098
          opacity: fadeOutBy(0.6),
2099
          child: Align(
2100 2101 2102
            // As the text shrinks, make sure it's still anchored to the leading
            // edge of a constantly sized outer box.
            alignment: AlignmentDirectional.centerStart,
2103
            child: DefaultTextStyleTransition(
2104
              style: animation.drive(TextStyleTween(
xster's avatar
xster committed
2105 2106
                begin: bottomLargeTitleTextStyle,
                end: topBackButtonTextStyle,
2107
              )),
2108 2109 2110 2111 2112 2113 2114 2115 2116
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              child: bottomLargeTitle.child,
            ),
          ),
        ),
      );
    }

2117
    if (topLeading != null) {
2118 2119
      // Unlike bottom middle, the bottom large title moves when it can't
      // transition to the top back label position.
2120 2121
      final RelativeRect from = positionInTransitionBox(bottomComponents.largeTitleKey, from: bottomNavBarBox);

2122
      final RelativeRectTween positionTween = RelativeRectTween(
2123
        begin: from,
2124 2125 2126 2127 2128 2129
        end: from.shift(
          Offset(
            forwardDirection * bottomNavBarBox.size.width / 4.0,
            0.0,
          ),
        ),
2130 2131
      );

2132 2133
      // Just shift slightly towards the trailing edge instead of moving to the
      // back label position.
2134
      return PositionedTransition(
2135
        rect: animation.drive(positionTween),
2136
        child: FadeTransition(
2137 2138
          opacity: fadeOutBy(0.4),
          // Keep the font when transitioning into a non-back-label leading.
2139
          child: DefaultTextStyle(
2140
            style: bottomLargeTitleTextStyle!,
2141 2142 2143 2144 2145 2146 2147 2148 2149
            child: bottomLargeTitle.child,
          ),
        ),
      );
    }

    return null;
  }

2150 2151
  Widget? get bottomTrailing {
    final KeyedSubtree? bottomTrailing = bottomComponents.trailingKey.currentWidget as KeyedSubtree?;
2152 2153 2154 2155 2156

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

2157
    return Positioned.fromRelativeRect(
2158
      rect: positionInTransitionBox(bottomComponents.trailingKey, from: bottomNavBarBox),
2159
      child: FadeTransition(
2160 2161 2162 2163 2164 2165
        opacity: fadeOutBy(0.6),
        child: bottomTrailing.child,
      ),
    );
  }

2166 2167
  Widget? get topLeading {
    final KeyedSubtree? topLeading = topComponents.leadingKey.currentWidget as KeyedSubtree?;
2168 2169 2170 2171 2172

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

2173
    return Positioned.fromRelativeRect(
2174
      rect: positionInTransitionBox(topComponents.leadingKey, from: topNavBarBox),
2175
      child: FadeTransition(
2176 2177 2178 2179 2180 2181
        opacity: fadeInFrom(0.6),
        child: topLeading.child,
      ),
    );
  }

2182 2183 2184
  Widget? get topBackChevron {
    final KeyedSubtree? topBackChevron = topComponents.backChevronKey.currentWidget as KeyedSubtree?;
    final KeyedSubtree? bottomBackChevron = bottomComponents.backChevronKey.currentWidget as KeyedSubtree?;
2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195

    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) {
2196
      final RenderBox topBackChevronBox = topComponents.backChevronKey.currentContext!.findRenderObject()! as RenderBox;
2197 2198 2199 2200 2201 2202
      from = to.shift(
        Offset(
          forwardDirection * topBackChevronBox.size.width * 2.0,
          0.0,
        ),
      );
2203 2204
    }

2205
    final RelativeRectTween positionTween = RelativeRectTween(
2206 2207 2208 2209
      begin: from,
      end: to,
    );

2210
    return PositionedTransition(
2211
      rect: animation.drive(positionTween),
2212
      child: FadeTransition(
2213
        opacity: fadeInFrom(bottomBackChevron == null ? 0.7 : 0.4),
2214
        child: DefaultTextStyle(
xster's avatar
xster committed
2215
          style: topBackButtonTextStyle,
2216 2217 2218 2219 2220 2221
          child: topBackChevron.child,
        ),
      ),
    );
  }

2222 2223 2224 2225
  Widget? get topBackLabel {
    final KeyedSubtree? bottomMiddle = bottomComponents.middleKey.currentWidget as KeyedSubtree?;
    final KeyedSubtree? bottomLargeTitle = bottomComponents.largeTitleKey.currentWidget as KeyedSubtree?;
    final KeyedSubtree? topBackLabel = topComponents.backLabelKey.currentWidget as KeyedSubtree?;
2226 2227 2228 2229 2230

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

2231
    final RenderAnimatedOpacity? topBackLabelOpacity =
2232
        topComponents.backLabelKey.currentContext?.findAncestorRenderObjectOfType<RenderAnimatedOpacity>();
2233

2234
    Animation<double>? midClickOpacity;
2235
    if (topBackLabelOpacity != null && topBackLabelOpacity.opacity.value < 1.0) {
2236
      midClickOpacity = animation.drive(Tween<double>(
2237 2238
        begin: 0.0,
        end: topBackLabelOpacity.opacity.value,
2239
      ));
2240 2241 2242 2243 2244 2245 2246 2247
    }

    // 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 &&
2248
        bottomLargeExpanded) {
2249 2250 2251 2252 2253
      return slideFromLeadingEdge(
        fromKey: bottomComponents.largeTitleKey,
        fromNavBarBox: bottomNavBarBox,
        toKey: topComponents.backLabelKey,
        toNavBarBox: topNavBarBox,
2254
        child: FadeTransition(
2255
          opacity: midClickOpacity ?? fadeInFrom(0.4),
2256
          child: DefaultTextStyleTransition(
2257
            style: animation.drive(TextStyleTween(
xster's avatar
xster committed
2258 2259
              begin: bottomLargeTitleTextStyle,
              end: topBackButtonTextStyle,
2260
            )),
2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            child: topBackLabel.child,
          ),
        ),
      );
    }

    // The topBackLabel always comes from the large title first if available
    // and expanded instead of middle.
2271
    if (bottomMiddle != null) {
2272 2273 2274 2275 2276
      return slideFromLeadingEdge(
        fromKey: bottomComponents.middleKey,
        fromNavBarBox: bottomNavBarBox,
        toKey: topComponents.backLabelKey,
        toNavBarBox: topNavBarBox,
2277
        child: FadeTransition(
2278
          opacity: midClickOpacity ?? fadeInFrom(0.3),
2279
          child: DefaultTextStyleTransition(
2280
            style: animation.drive(TextStyleTween(
xster's avatar
xster committed
2281 2282
              begin: bottomTitleTextStyle,
              end: topBackButtonTextStyle,
2283
            )),
2284 2285 2286 2287 2288 2289 2290 2291 2292
            child: topBackLabel.child,
          ),
        ),
      );
    }

    return null;
  }

2293 2294
  Widget? get topMiddle {
    final KeyedSubtree? topMiddle = topComponents.middleKey.currentWidget as KeyedSubtree?;
2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306

    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);
2307 2308 2309 2310 2311 2312 2313 2314 2315 2316
    final RenderBox toBox = topComponents.middleKey.currentContext!.findRenderObject()! as RenderBox;

    final bool isLTR = forwardDirection > 0;

    // Anchor is the top-leading point of toBox, in transition box's top-leading
    // coordinate space.
    final Offset toAnchorInTransitionBox = Offset(
      isLTR ? to.left : to.right,
      to.top,
    );
2317 2318

    // Shift in from the trailing edge of the screen.
2319 2320 2321 2322 2323 2324
    final Tween<Offset> anchorMovementInTransitionBox = Tween<Offset>(
      begin: Offset(
        // the "width / 2" here makes the middle widget's horizontal center on
        // the trailing edge of the top nav bar.
        topNavBarBox.size.width - toBox.size.width / 2,
        to.top,
2325
      ),
2326
      end: toAnchorInTransitionBox,
2327 2328
    );

2329 2330 2331 2332
    return _FixedSizeSlidingTransition(
      isLTR: isLTR,
      offsetAnimation: animation.drive(anchorMovementInTransitionBox),
      size: toBox.size,
2333
      child: FadeTransition(
2334
        opacity: fadeInFrom(0.25),
2335
        child: DefaultTextStyle(
xster's avatar
xster committed
2336
          style: topTitleTextStyle,
2337 2338 2339 2340 2341 2342
          child: topMiddle.child,
        ),
      ),
    );
  }

2343 2344
  Widget? get topTrailing {
    final KeyedSubtree? topTrailing = topComponents.trailingKey.currentWidget as KeyedSubtree?;
2345 2346 2347 2348 2349

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

2350
    return Positioned.fromRelativeRect(
2351
      rect: positionInTransitionBox(topComponents.trailingKey, from: topNavBarBox),
2352
      child: FadeTransition(
2353 2354 2355 2356 2357 2358
        opacity: fadeInFrom(0.4),
        child: topTrailing.child,
      ),
    );
  }

2359 2360
  Widget? get topLargeTitle {
    final KeyedSubtree? topLargeTitle = topComponents.largeTitleKey.currentWidget as KeyedSubtree?;
2361 2362 2363 2364 2365 2366 2367 2368

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

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

    // Shift in from the trailing edge of the screen.
2369
    final RelativeRectTween positionTween = RelativeRectTween(
2370 2371 2372 2373 2374 2375
      begin: to.shift(
        Offset(
          forwardDirection * topNavBarBox.size.width,
          0.0,
        ),
      ),
2376 2377 2378
      end: to,
    );

2379
    return PositionedTransition(
2380
      rect: animation.drive(positionTween),
2381
      child: FadeTransition(
2382
        opacity: fadeInFrom(0.3),
2383
        child: DefaultTextStyle(
2384
          style: topLargeTitleTextStyle!,
2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395
          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.
2396
RectTween _linearTranslateWithLargestRectSizeTween(Rect? begin, Rect? end) {
2397
  final Size largestSize = Size(
2398
    math.max(begin!.size.width, end!.size.width),
2399 2400
    math.max(begin.size.height, end.size.height),
  );
2401
  return RectTween(
2402 2403 2404
    begin: begin.topLeft & largestSize,
    end: end.topLeft & largestSize,
  );
2405
}
2406

2407
Widget _navBarHeroLaunchPadBuilder(
2408
  BuildContext context,
2409
  Size heroSize,
2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423
  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.
2424
  return Visibility(
2425 2426 2427 2428 2429 2430
    maintainSize: true,
    maintainAnimation: true,
    maintainState: true,
    visible: false,
    child: child,
  );
2431
}
2432 2433

/// Navigation bars' hero flight shuttle builder.
2434
Widget _navBarHeroFlightShuttleBuilder(
2435 2436 2437 2438 2439 2440 2441 2442 2443
  BuildContext flightContext,
  Animation<double> animation,
  HeroFlightDirection flightDirection,
  BuildContext fromHeroContext,
  BuildContext toHeroContext,
) {
  assert(fromHeroContext.widget is Hero);
  assert(toHeroContext.widget is Hero);

2444 2445
  final Hero fromHeroWidget = fromHeroContext.widget as Hero;
  final Hero toHeroWidget = toHeroContext.widget as Hero;
2446 2447 2448 2449

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

2450 2451
  final _TransitionableNavigationBar fromNavBar = fromHeroWidget.child as _TransitionableNavigationBar;
  final _TransitionableNavigationBar toNavBar = toHeroWidget.child as _TransitionableNavigationBar;
2452 2453 2454


  assert(
2455
    fromNavBar.componentsKeys.navBarBoxKey.currentContext!.owner != null,
2456 2457 2458
    'The from nav bar to Hero must have been mounted in the previous frame',
  );
  assert(
2459
    toNavBar.componentsKeys.navBarBoxKey.currentContext!.owner != null,
2460 2461 2462 2463 2464
    'The to nav bar to Hero must have been mounted in the previous frame',
  );

  switch (flightDirection) {
    case HeroFlightDirection.push:
2465
      return _NavigationBarTransition(
2466 2467 2468 2469 2470
        animation: animation,
        bottomNavBar: fromNavBar,
        topNavBar: toNavBar,
      );
    case HeroFlightDirection.pop:
2471
      return _NavigationBarTransition(
2472 2473 2474 2475 2476
        animation: animation,
        bottomNavBar: toNavBar,
        topNavBar: fromNavBar,
      );
  }
2477
}