route.dart 48.9 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';
6
import 'dart:ui' show ImageFilter, lerpDouble;
7

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

13
import 'colors.dart';
14
import 'interface_level.dart';
15
import 'localizations.dart';
16

17 18
const double _kBackGestureWidth = 20.0;
const double _kMinFlingVelocity = 1.0; // Screen widths per second.
19

20 21 22 23 24 25 26 27
// An eyeballed value for the maximum time it takes for a page to animate forward
// if the user releases a page mid swipe.
const int _kMaxDroppedSwipePageForwardAnimationTime = 800; // Milliseconds.

// The maximum time for a page to get reset to it's original position if the
// user releases a page mid swipe.
const int _kMaxPageBackAnimationTime = 300; // Milliseconds.

28 29 30 31 32 33 34 35 36 37 38 39 40
/// Barrier color used for a barrier visible during transitions for Cupertino
/// page routes.
///
/// This barrier color is only used for full-screen page routes with
/// `fullscreenDialog: false`.
///
/// By default, `fullscreenDialog` Cupertino route transitions have no
/// `barrierColor`, and [CupertinoDialogRoute]s and [CupertinoModalPopupRoute]s
/// have a `barrierColor` defined by [kCupertinoModalBarrierColor].
///
/// A relatively rigorous eyeball estimation.
const Color _kCupertinoPageTransitionBarrierColor = Color(0x18000000);

41 42 43 44
/// Barrier color for a Cupertino modal barrier.
///
/// Extracted from https://developer.apple.com/design/resources/.
const Color kCupertinoModalBarrierColor = CupertinoDynamicColor.withBrightness(
45 46 47
  color: Color(0x33000000),
  darkColor: Color(0x7A000000),
);
48

49 50 51
// The duration of the transition used when a modal popup is shown.
const Duration _kModalPopupTransitionDuration = Duration(milliseconds: 335);

52
// Offset from offscreen to the right to fully on screen.
53
final Animatable<Offset> _kRightMiddleTween = Tween<Offset>(
54 55
  begin: const Offset(1.0, 0.0),
  end: Offset.zero,
56 57
);

58
// Offset from fully on screen to 1/3 offscreen to the left.
59
final Animatable<Offset> _kMiddleLeftTween = Tween<Offset>(
60 61
  begin: Offset.zero,
  end: const Offset(-1.0/3.0, 0.0),
62 63
);

64
// Offset from offscreen below to fully on screen.
65
final Animatable<Offset> _kBottomUpTween = Tween<Offset>(
66 67
  begin: const Offset(0.0, 1.0),
  end: Offset.zero,
68 69
);

70 71
/// A mixin that replaces the entire screen with an iOS transition for a
/// [PageRoute].
72
///
73
/// {@template flutter.cupertino.cupertinoRouteTransitionMixin}
74 75
/// The page slides in from the right and exits in reverse. The page also shifts
/// to the left in parallax when another page enters to cover it.
76
///
77 78
/// The page slides in from the bottom and exits in reverse with no parallax
/// effect for fullscreen dialogs.
79
/// {@endtemplate}
80
///
81 82
/// See also:
///
83
///  * [MaterialRouteTransitionMixin], which is a mixin that provides
84
///    platform-appropriate transitions for a [PageRoute].
85 86
///  * [CupertinoPageRoute], which is a [PageRoute] that leverages this mixin.
mixin CupertinoRouteTransitionMixin<T> on PageRoute<T> {
87
  /// Builds the primary contents of the route.
88 89
  @protected
  Widget buildContent(BuildContext context);
90

91
  /// {@template flutter.cupertino.CupertinoRouteTransitionMixin.title}
92 93
  /// A title string for this route.
  ///
94
  /// Used to auto-populate [CupertinoNavigationBar] and
95 96
  /// [CupertinoSliverNavigationBar]'s `middle`/`largeTitle` widgets when
  /// one is not manually supplied.
97
  /// {@endtemplate}
98
  String? get title;
99

100
  ValueNotifier<String?>? _previousTitle;
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115

  /// The title string of the previous [CupertinoPageRoute].
  ///
  /// The [ValueListenable]'s value is readable after the route is installed
  /// onto a [Navigator]. The [ValueListenable] will also notify its listeners
  /// if the value changes (such as by replacing the previous route).
  ///
  /// The [ValueListenable] itself will be null before the route is installed.
  /// Its content value will be null if the previous route has no title or
  /// is not a [CupertinoPageRoute].
  ///
  /// See also:
  ///
  ///  * [ValueListenableBuilder], which can be used to listen and rebuild
  ///    widgets based on a ValueListenable.
116
  ValueListenable<String?> get previousTitle {
117 118 119 120
    assert(
      _previousTitle != null,
      'Cannot read the previousTitle for a route that has not yet been installed',
    );
121
    return _previousTitle!;
122 123
  }

124 125 126 127 128 129
  @override
  void dispose() {
    _previousTitle?.dispose();
    super.dispose();
  }

130
  @override
131 132
  void didChangePrevious(Route<dynamic>? previousRoute) {
    final String? previousTitleString = previousRoute is CupertinoRouteTransitionMixin
133 134
      ? previousRoute.title
      : null;
135
    if (_previousTitle == null) {
136
      _previousTitle = ValueNotifier<String?>(previousTitleString);
137
    } else {
138
      _previousTitle!.value = previousTitleString;
139 140 141 142
    }
    super.didChangePrevious(previousRoute);
  }

143
  @override
144
  // A relatively rigorous eyeball estimation.
145
  Duration get transitionDuration => const Duration(milliseconds: 500);
146 147

  @override
148
  Color? get barrierColor => fullscreenDialog ? null : _kCupertinoPageTransitionBarrierColor;
149

150
  @override
151
  String? get barrierLabel => null;
152

153
  @override
154 155
  bool canTransitionTo(TransitionRoute<dynamic> nextRoute) {
    // Don't perform outgoing animation if the next route is a fullscreen dialog.
156
    return nextRoute is CupertinoRouteTransitionMixin && !nextRoute.fullscreenDialog;
157 158
  }

159 160 161
  /// True if an iOS-style back swipe pop gesture is currently underway for [route].
  ///
  /// This just check the route's [NavigatorState.userGestureInProgress].
162
  ///
163 164 165 166
  /// See also:
  ///
  ///  * [popGestureEnabled], which returns true if a user-triggered pop gesture
  ///    would be allowed.
167
  static bool isPopGestureInProgress(PageRoute<dynamic> route) {
168
    return route.navigator!.userGestureInProgress;
169
  }
170

171
  /// True if an iOS-style back swipe pop gesture is currently underway for this route.
172 173 174
  ///
  /// See also:
  ///
175 176 177 178 179
  ///  * [isPopGestureInProgress], which returns true if a Cupertino pop gesture
  ///    is currently underway for specific route.
  ///  * [popGestureEnabled], which returns true if a user-triggered pop gesture
  ///    would be allowed.
  bool get popGestureInProgress => isPopGestureInProgress(this);
180

181
  /// Whether a pop gesture can be started by the user.
182
  ///
183
  /// Returns true if the user can edge-swipe to a previous route.
184
  ///
185 186
  /// Returns false once [isPopGestureInProgress] is true, but
  /// [isPopGestureInProgress] can only become true if [popGestureEnabled] was
187
  /// true first.
188
  ///
189
  /// This should only be used between frames, not during build.
190 191 192
  bool get popGestureEnabled => _isPopGestureEnabled(this);

  static bool _isPopGestureEnabled<T>(PageRoute<T> route) {
193 194
    // If there's nothing to go back to, then obviously we don't support
    // the back gesture.
195
    if (route.isFirst) {
196
      return false;
197
    }
198 199
    // If the route wouldn't actually pop if we popped it, then the gesture
    // would be really confusing (or would skip internal routes), so disallow it.
200
    if (route.willHandlePopInternally) {
201
      return false;
202
    }
203 204
    // If attempts to dismiss this route might be vetoed such as in a page
    // with forms, then do not allow the user to dismiss the route with a swipe.
205 206
    if (route.hasScopedWillPopCallback
        || route.popDisposition == RoutePopDisposition.doNotPop) {
207
      return false;
208
    }
209
    // Fullscreen dialogs aren't dismissible by back swipe.
210
    if (route.fullscreenDialog) {
211
      return false;
212
    }
213
    // If we're in an animation already, we cannot be manually swiped.
214
    if (route.animation!.status != AnimationStatus.completed) {
215
      return false;
216
    }
217 218 219
    // If we're being popped into, we also cannot be swiped until the pop above
    // it completes. This translates to our secondary animation being
    // dismissed.
220
    if (route.secondaryAnimation!.status != AnimationStatus.dismissed) {
221
      return false;
222
    }
223
    // If we're in a gesture already, we cannot start another.
224
    if (isPopGestureInProgress(route)) {
225
      return false;
226
    }
227

228 229 230
    // Looks like a back gesture would be welcome!
    return true;
  }
231

232
  @override
233
  Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
234
    final Widget child = buildContent(context);
235
    return Semantics(
236 237
      scopesRoute: true,
      explicitChildNodes: true,
238
      child: child,
239
    );
240
  }
241

242
  // Called by _CupertinoBackGestureDetector when a pop ("back") drag start
xster's avatar
xster committed
243
  // gesture is detected. The returned controller handles all of the subsequent
244 245 246 247
  // drag events.
  static _CupertinoBackGestureController<T> _startPopGesture<T>(PageRoute<T> route) {
    assert(_isPopGestureEnabled(route));

248
    return _CupertinoBackGestureController<T>(
249 250
      navigator: route.navigator!,
      controller: route.controller!, // protected access
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
    );
  }

  /// Returns a [CupertinoFullscreenDialogTransition] if [route] is a full
  /// screen dialog, otherwise a [CupertinoPageTransition] is returned.
  ///
  /// Used by [CupertinoPageRoute.buildTransitions].
  ///
  /// This method can be applied to any [PageRoute], not just
  /// [CupertinoPageRoute]. It's typically used to provide a Cupertino style
  /// horizontal transition for material widgets when the target platform
  /// is [TargetPlatform.iOS].
  ///
  /// See also:
  ///
  ///  * [CupertinoPageTransitionsBuilder], which uses this method to define a
  ///    [PageTransitionsBuilder] for the [PageTransitionsTheme].
  static Widget buildPageTransitions<T>(
    PageRoute<T> route,
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
    Widget child,
  ) {
275 276 277 278 279 280
    // Check if the route has an animation that's currently participating
    // in a back swipe gesture.
    //
    // In the middle of a back gesture drag, let the transition be linear to
    // match finger motions.
    final bool linearTransition = isPopGestureInProgress(route);
281
    if (route.fullscreenDialog) {
282
      return CupertinoFullscreenDialogTransition(
283 284 285
        primaryRouteAnimation: animation,
        secondaryRouteAnimation: secondaryAnimation,
        linearTransition: linearTransition,
286
        child: child,
287
      );
288
    } else {
289
      return CupertinoPageTransition(
290 291
        primaryRouteAnimation: animation,
        secondaryRouteAnimation: secondaryAnimation,
292
        linearTransition: linearTransition,
293
        child: _CupertinoBackGestureDetector<T>(
294 295
          enabledCallback: () => _isPopGestureEnabled<T>(route),
          onStartPopGesture: () => _startPopGesture<T>(route),
296 297
          child: child,
        ),
298
      );
299
    }
300
  }
301

302 303 304 305
  @override
  Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
    return buildPageTransitions<T>(this, context, animation, secondaryAnimation, child);
  }
306 307 308 309 310 311 312 313 314 315 316 317 318 319
}

/// A modal route that replaces the entire screen with an iOS transition.
///
/// {@macro flutter.cupertino.cupertinoRouteTransitionMixin}
///
/// By default, when a modal route is replaced by another, the previous route
/// remains in memory. To free all the resources when this is not necessary, set
/// [maintainState] to false.
///
/// The type `T` specifies the return type of the route which can be supplied as
/// the route is popped from the stack via [Navigator.pop] when an optional
/// `result` can be provided.
///
320 321 322
/// If `barrierDismissible` is true, then pressing the escape key on the keyboard
/// will cause the current route to be popped with null as the value.
///
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
/// See also:
///
///  * [CupertinoRouteTransitionMixin], for a mixin that provides iOS transition
///    for this modal route.
///  * [MaterialPageRoute], for an adaptive [PageRoute] that uses a
///    platform-appropriate transition.
///  * [CupertinoPageScaffold], for applications that have one page with a fixed
///    navigation bar on top.
///  * [CupertinoTabScaffold], for applications that have a tab bar at the
///    bottom with multiple pages.
///  * [CupertinoPage], for a [Page] version of this class.
class CupertinoPageRoute<T> extends PageRoute<T> with CupertinoRouteTransitionMixin<T> {
  /// Creates a page route for use in an iOS designed app.
  ///
  /// The [builder], [maintainState], and [fullscreenDialog] arguments must not
  /// be null.
  CupertinoPageRoute({
340
    required this.builder,
341
    this.title,
342
    super.settings,
343
    this.maintainState = true,
344
    super.fullscreenDialog,
345
    super.allowSnapshotting = true,
346
    super.barrierDismissible = false,
347
  }) {
348 349
    assert(opaque);
  }
350

351
  /// Builds the primary contents of the route.
352 353
  final WidgetBuilder builder;

354 355 356
  @override
  Widget buildContent(BuildContext context) => builder(context);

357
  @override
358
  final String? title;
359 360 361

  @override
  final bool maintainState;
362

363 364
  @override
  String get debugLabel => '${super.debugLabel}(${settings.name})';
365 366
}

367 368 369 370 371 372
// A page-based version of CupertinoPageRoute.
//
// This route uses the builder from the page to build its content. This ensures
// the content is up to date after page updates.
class _PageBasedCupertinoPageRoute<T> extends PageRoute<T> with CupertinoRouteTransitionMixin<T> {
  _PageBasedCupertinoPageRoute({
373
    required CupertinoPage<T> page,
374
    super.allowSnapshotting = true,
375
  }) : super(settings: page) {
376 377
    assert(opaque);
  }
378 379 380 381

  CupertinoPage<T> get _page => settings as CupertinoPage<T>;

  @override
382
  Widget buildContent(BuildContext context) => _page.child;
383 384

  @override
385
  String? get title => _page.title;
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415

  @override
  bool get maintainState => _page.maintainState;

  @override
  bool get fullscreenDialog => _page.fullscreenDialog;

  @override
  String get debugLabel => '${super.debugLabel}(${_page.name})';
}

/// A page that creates a cupertino style [PageRoute].
///
/// {@macro flutter.cupertino.cupertinoRouteTransitionMixin}
///
/// By default, when a created modal route is replaced by another, the previous
/// route remains in memory. To free all the resources when this is not
/// necessary, set [maintainState] to false.
///
/// The type `T` specifies the return type of the route which can be supplied as
/// the route is popped from the stack via [Navigator.transitionDelegate] by
/// providing the optional `result` argument to the
/// [RouteTransitionRecord.markForPop] in the [TransitionDelegate.resolve].
///
/// See also:
///
///  * [CupertinoPageRoute], for a [PageRoute] version of this class.
class CupertinoPage<T> extends Page<T> {
  /// Creates a cupertino page.
  const CupertinoPage({
416
    required this.child,
417 418 419
    this.maintainState = true,
    this.title,
    this.fullscreenDialog = false,
420
    this.allowSnapshotting = true,
421 422 423 424
    super.key,
    super.name,
    super.arguments,
    super.restorationId,
425
  });
426

427 428
  /// The content to be shown in the [Route] created by this page.
  final Widget child;
429

430
  /// {@macro flutter.cupertino.CupertinoRouteTransitionMixin.title}
431
  final String? title;
432

433
  /// {@macro flutter.widgets.ModalRoute.maintainState}
434 435
  final bool maintainState;

436
  /// {@macro flutter.widgets.PageRoute.fullscreenDialog}
437 438
  final bool fullscreenDialog;

439 440
  /// {@macro flutter.widgets.TransitionRoute.allowSnapshotting}
  final bool allowSnapshotting;
441

442 443
  @override
  Route<T> createRoute(BuildContext context) {
444
    return _PageBasedCupertinoPageRoute<T>(page: this, allowSnapshotting: allowSnapshotting);
445 446 447
  }
}

448
/// Provides an iOS-style page transition animation.
449 450 451
///
/// The page slides in from the right and exits in reverse. It also shifts to the left in
/// a parallax motion when another page enters to cover it.
452
class CupertinoPageTransition extends StatelessWidget {
453 454 455 456 457 458
  /// Creates an iOS-style page transition.
  ///
  ///  * `primaryRouteAnimation` is a linear route animation from 0.0 to 1.0
  ///    when this screen is being pushed.
  ///  * `secondaryRouteAnimation` is a linear route animation from 0.0 to 1.0
  ///    when another screen is being pushed on top of this one.
459
  ///  * `linearTransition` is whether to perform the transitions linearly.
460
  ///    Used to precisely track back gesture drags.
461
  CupertinoPageTransition({
462
    super.key,
463 464 465 466
    required Animation<double> primaryRouteAnimation,
    required Animation<double> secondaryRouteAnimation,
    required this.child,
    required bool linearTransition,
467
  }) : _primaryPositionAnimation =
468 469 470 471
           (linearTransition
             ? primaryRouteAnimation
             : CurvedAnimation(
                 parent: primaryRouteAnimation,
472 473
                 curve: Curves.fastEaseInToSlowEaseOut,
                 reverseCurve: Curves.fastEaseInToSlowEaseOut.flipped,
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
               )
           ).drive(_kRightMiddleTween),
       _secondaryPositionAnimation =
           (linearTransition
             ? secondaryRouteAnimation
             : CurvedAnimation(
                 parent: secondaryRouteAnimation,
                 curve: Curves.linearToEaseOut,
                 reverseCurve: Curves.easeInToLinear,
               )
           ).drive(_kMiddleLeftTween),
       _primaryShadowAnimation =
           (linearTransition
             ? primaryRouteAnimation
             : CurvedAnimation(
                 parent: primaryRouteAnimation,
                 curve: Curves.linearToEaseOut,
               )
492
           ).drive(_CupertinoEdgeShadowDecoration.kTween);
493 494

  // When this page is coming in to cover another page.
495
  final Animation<Offset> _primaryPositionAnimation;
496
  // When this page is becoming covered by another page.
497
  final Animation<Offset> _secondaryPositionAnimation;
498
  final Animation<Decoration> _primaryShadowAnimation;
499 500

  /// The widget below this widget in the tree.
501 502 503 504
  final Widget child;

  @override
  Widget build(BuildContext context) {
Ian Hickson's avatar
Ian Hickson committed
505
    assert(debugCheckHasDirectionality(context));
506
    final TextDirection textDirection = Directionality.of(context);
507
    return SlideTransition(
508
      position: _secondaryPositionAnimation,
Ian Hickson's avatar
Ian Hickson committed
509
      textDirection: textDirection,
510
      transformHitTests: false,
511
      child: SlideTransition(
512
        position: _primaryPositionAnimation,
Ian Hickson's avatar
Ian Hickson committed
513
        textDirection: textDirection,
514
        child: DecoratedBoxTransition(
515
          decoration: _primaryShadowAnimation,
516 517 518
          child: child,
        ),
      ),
519 520 521 522
    );
  }
}

523 524 525 526
/// An iOS-style transition used for summoning fullscreen dialogs.
///
/// For example, used when creating a new calendar event by bringing in the next
/// screen from the bottom.
527
class CupertinoFullscreenDialogTransition extends StatelessWidget {
528
  /// Creates an iOS-style transition used for summoning fullscreen dialogs.
529 530 531 532 533 534 535
  ///
  ///  * `primaryRouteAnimation` is a linear route animation from 0.0 to 1.0
  ///    when this screen is being pushed.
  ///  * `secondaryRouteAnimation` is a linear route animation from 0.0 to 1.0
  ///    when another screen is being pushed on top of this one.
  ///  * `linearTransition` is whether to perform the secondary transition linearly.
  ///    Used to precisely track back gesture drags.
536
  CupertinoFullscreenDialogTransition({
537
    super.key,
538 539 540 541
    required Animation<double> primaryRouteAnimation,
    required Animation<double> secondaryRouteAnimation,
    required this.child,
    required bool linearTransition,
542
  }) : _positionAnimation = CurvedAnimation(
543
         parent: primaryRouteAnimation,
544 545 546 547 548
         curve: Curves.linearToEaseOut,
         // The curve must be flipped so that the reverse animation doesn't play
         // an ease-in curve, which iOS does not use.
         reverseCurve: Curves.linearToEaseOut.flipped,
       ).drive(_kBottomUpTween),
549 550 551 552 553 554 555 556
       _secondaryPositionAnimation =
           (linearTransition
             ? secondaryRouteAnimation
             : CurvedAnimation(
                 parent: secondaryRouteAnimation,
                 curve: Curves.linearToEaseOut,
                 reverseCurve: Curves.easeInToLinear,
               )
557
           ).drive(_kMiddleLeftTween);
558

559
  final Animation<Offset> _positionAnimation;
560 561
  // When this page is becoming covered by another page.
  final Animation<Offset> _secondaryPositionAnimation;
562 563

  /// The widget below this widget in the tree.
564
  final Widget child;
565 566

  @override
567
  Widget build(BuildContext context) {
568
    assert(debugCheckHasDirectionality(context));
569
    final TextDirection textDirection = Directionality.of(context);
570
    return SlideTransition(
571 572 573 574 575 576 577
      position: _secondaryPositionAnimation,
      textDirection: textDirection,
      transformHitTests: false,
      child: SlideTransition(
        position: _positionAnimation,
        child: child,
      ),
578
    );
579 580 581
  }
}

582 583 584 585 586
/// This is the widget side of [_CupertinoBackGestureController].
///
/// This widget provides a gesture recognizer which, when it determines the
/// route can be closed with a back gesture, creates the controller and
/// feeds it the input from the gesture recognizer.
Ian Hickson's avatar
Ian Hickson committed
587 588 589
///
/// The gesture data is converted from absolute coordinates to logical
/// coordinates by this widget.
590 591 592 593
///
/// The type `T` specifies the return type of the route with which this gesture
/// detector is associated.
class _CupertinoBackGestureDetector<T> extends StatefulWidget {
594
  const _CupertinoBackGestureDetector({
595
    super.key,
596 597 598
    required this.enabledCallback,
    required this.onStartPopGesture,
    required this.child,
599
  });
600 601 602 603 604

  final Widget child;

  final ValueGetter<bool> enabledCallback;

605
  final ValueGetter<_CupertinoBackGestureController<T>> onStartPopGesture;
606 607

  @override
608
  _CupertinoBackGestureDetectorState<T> createState() => _CupertinoBackGestureDetectorState<T>();
609 610
}

611
class _CupertinoBackGestureDetectorState<T> extends State<_CupertinoBackGestureDetector<T>> {
612
  _CupertinoBackGestureController<T>? _backGestureController;
613

614
  late HorizontalDragGestureRecognizer _recognizer;
615 616 617 618

  @override
  void initState() {
    super.initState();
619
    _recognizer = HorizontalDragGestureRecognizer(debugOwner: this)
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
      ..onStart = _handleDragStart
      ..onUpdate = _handleDragUpdate
      ..onEnd = _handleDragEnd
      ..onCancel = _handleDragCancel;
  }

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

  void _handleDragStart(DragStartDetails details) {
    assert(mounted);
    assert(_backGestureController == null);
    _backGestureController = widget.onStartPopGesture();
  }

  void _handleDragUpdate(DragUpdateDetails details) {
    assert(mounted);
    assert(_backGestureController != null);
641
    _backGestureController!.dragUpdate(_convertToLogical(details.primaryDelta! / context.size!.width));
642 643 644 645 646
  }

  void _handleDragEnd(DragEndDetails details) {
    assert(mounted);
    assert(_backGestureController != null);
647
    _backGestureController!.dragEnd(_convertToLogical(details.velocity.pixelsPerSecond.dx / context.size!.width));
648 649 650 651 652 653 654 655 656 657 658 659
    _backGestureController = null;
  }

  void _handleDragCancel() {
    assert(mounted);
    // This can be called even if start is not called, paired with the "down" event
    // that we don't consider here.
    _backGestureController?.dragEnd(0.0);
    _backGestureController = null;
  }

  void _handlePointerDown(PointerDownEvent event) {
660
    if (widget.enabledCallback()) {
661
      _recognizer.addPointer(event);
662
    }
663 664
  }

Ian Hickson's avatar
Ian Hickson committed
665
  double _convertToLogical(double value) {
666
    switch (Directionality.of(context)) {
Ian Hickson's avatar
Ian Hickson committed
667 668 669 670 671 672 673
      case TextDirection.rtl:
        return -value;
      case TextDirection.ltr:
        return value;
    }
  }

674 675
  @override
  Widget build(BuildContext context) {
Ian Hickson's avatar
Ian Hickson committed
676
    assert(debugCheckHasDirectionality(context));
677 678 679
    // For devices with notches, the drag area needs to be larger on the side
    // that has the notch.
    double dragAreaWidth = Directionality.of(context) == TextDirection.ltr ?
680 681
                           MediaQuery.paddingOf(context).left :
                           MediaQuery.paddingOf(context).right;
682
    dragAreaWidth = max(dragAreaWidth, _kBackGestureWidth);
683
    return Stack(
684 685 686
      fit: StackFit.passthrough,
      children: <Widget>[
        widget.child,
687
        PositionedDirectional(
Ian Hickson's avatar
Ian Hickson committed
688
          start: 0.0,
689
          width: dragAreaWidth,
690 691
          top: 0.0,
          bottom: 0.0,
692
          child: Listener(
693 694 695
            onPointerDown: _handlePointerDown,
            behavior: HitTestBehavior.translucent,
          ),
696 697 698 699 700 701
        ),
      ],
    );
  }
}

702 703
/// A controller for an iOS-style back gesture.
///
704 705 706 707
/// This is created by a [CupertinoPageRoute] in response from a gesture caught
/// by a [_CupertinoBackGestureDetector] widget, which then also feeds it input
/// from the gesture. It controls the animation controller owned by the route,
/// based on the input provided by the gesture detector.
Ian Hickson's avatar
Ian Hickson committed
708 709 710
///
/// This class works entirely in logical coordinates (0.0 is new page dismissed,
/// 1.0 is new page on top).
711 712 713 714
///
/// The type `T` specifies the return type of the route with which this gesture
/// detector controller is associated.
class _CupertinoBackGestureController<T> {
715
  /// Creates a controller for an iOS-style back gesture.
716
  _CupertinoBackGestureController({
717 718
    required this.navigator,
    required this.controller,
719
  }) {
720
    navigator.didStartUserGesture();
721 722
  }

723
  final AnimationController controller;
724
  final NavigatorState navigator;
725 726 727

  /// The drag gesture has changed by [fractionalDelta]. The total range of the
  /// drag should be 0.0 to 1.0.
728 729 730 731
  void dragUpdate(double delta) {
    controller.value -= delta;
  }

732 733 734 735
  /// The drag gesture has ended with a horizontal motion of
  /// [fractionalVelocity] as a fraction of screen width per second.
  void dragEnd(double velocity) {
    // Fling in the appropriate direction.
736 737 738 739
    //
    // This curve has been determined through rigorously eyeballing native iOS
    // animations.
    const Curve animationCurve = Curves.fastLinearToSlowEaseIn;
740
    final bool animateForward;
741 742 743 744

    // If the user releases the page before mid screen with sufficient velocity,
    // or after mid screen, we should animate the page out. Otherwise, the page
    // should be animated back in.
745
    if (velocity.abs() >= _kMinFlingVelocity) {
746
      animateForward = velocity <= 0;
747
    } else {
748
      animateForward = controller.value > 0.5;
749
    }
750

751 752 753 754
    if (animateForward) {
      // The closer the panel is to dismissing, the shorter the animation is.
      // We want to cap the animation time, but we want to use a linear curve
      // to determine it.
755
      final int droppedPageForwardAnimationTime = min(
756
        lerpDouble(_kMaxDroppedSwipePageForwardAnimationTime, 0, controller.value)!.floor(),
757 758
        _kMaxPageBackAnimationTime,
      );
759
      controller.animateTo(1.0, duration: Duration(milliseconds: droppedPageForwardAnimationTime), curve: animationCurve);
760
    } else {
761 762 763 764 765 766
      // This route is destined to pop at this point. Reuse navigator's pop.
      navigator.pop();

      // The popping may have finished inline if already at the target destination.
      if (controller.isAnimating) {
        // Otherwise, use a custom popping animation duration and curve.
767
        final int droppedPageBackAnimationTime = lerpDouble(0, _kMaxDroppedSwipePageForwardAnimationTime, controller.value)!.floor();
768 769
        controller.animateBack(0.0, duration: Duration(milliseconds: droppedPageBackAnimationTime), curve: animationCurve);
      }
770
    }
771

772
    if (controller.isAnimating) {
773 774 775
      // Keep the userGestureInProgress in true state so we don't change the
      // curve of the page transition mid-flight since CupertinoPageTransition
      // depends on userGestureInProgress.
776
      late AnimationStatusListener animationStatusCallback;
777 778 779 780 781
      animationStatusCallback = (AnimationStatus status) {
        navigator.didStopUserGesture();
        controller.removeStatusListener(animationStatusCallback);
      };
      controller.addStatusListener(animationStatusCallback);
782 783
    } else {
      navigator.didStopUserGesture();
784
    }
785 786
  }
}
787

Ian Hickson's avatar
Ian Hickson committed
788 789 790
// A custom [Decoration] used to paint an extra shadow on the start edge of the
// box it's decorating. It's like a [BoxDecoration] with only a gradient except
// it paints on the start side of the box instead of behind the box.
791
class _CupertinoEdgeShadowDecoration extends Decoration {
792
  const _CupertinoEdgeShadowDecoration._([this._colors]);
793

794 795 796 797 798 799 800 801 802 803
  static DecorationTween kTween = DecorationTween(
    begin: const _CupertinoEdgeShadowDecoration._(), // No decoration initially.
    end: const _CupertinoEdgeShadowDecoration._(
      // Eyeballed gradient used to mimic a drop shadow on the start side only.
      <Color>[
        Color(0x04000000),
        Color(0x00000000),
      ],
    ),
  );
804

805 806 807 808 809 810 811 812 813 814 815
  // Colors used to paint a gradient at the start edge of the box it is
  // decorating.
  //
  // The first color in the list is used at the start of the gradient, which
  // is located at the start edge of the decorated box.
  //
  // If this is null, no shadow is drawn.
  //
  // The list must have at least two colors in it (otherwise it would not be a
  // gradient).
  final List<Color>? _colors;
816

817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
  // Linearly interpolate between two edge shadow decorations decorations.
  //
  // The `t` argument represents position on the timeline, with 0.0 meaning
  // that the interpolation has not started, returning `a` (or something
  // equivalent to `a`), 1.0 meaning that the interpolation has finished,
  // returning `b` (or something equivalent to `b`), and values in between
  // meaning that the interpolation is at the relevant point on the timeline
  // between `a` and `b`. The interpolation can be extrapolated beyond 0.0 and
  // 1.0, so negative values and values greater than 1.0 are valid (and can
  // easily be generated by curves such as [Curves.elasticInOut]).
  //
  // Values for `t` are usually obtained from an [Animation<double>], such as
  // an [AnimationController].
  //
  // See also:
  //
  //  * [Decoration.lerp].
834 835 836
  static _CupertinoEdgeShadowDecoration? lerp(
    _CupertinoEdgeShadowDecoration? a,
    _CupertinoEdgeShadowDecoration? b,
837
    double t,
838
  ) {
839 840
    if (identical(a, b)) {
      return a;
841 842
    }
    if (a == null) {
843
      return b!._colors == null ? b : _CupertinoEdgeShadowDecoration._(b._colors!.map<Color>((Color color) => Color.lerp(null, color, t)!).toList());
844 845
    }
    if (b == null) {
846
      return a._colors == null ? a : _CupertinoEdgeShadowDecoration._(a._colors.map<Color>((Color color) => Color.lerp(null, color, 1.0 - t)!).toList());
847
    }
848 849 850
    assert(b._colors != null || a._colors != null);
    // If it ever becomes necessary, we could allow decorations with different
    // length' here, similarly to how it is handled in [LinearGradient.lerp].
851
    assert(b._colors == null || a._colors == null || a._colors.length == b._colors.length);
852 853 854
    return _CupertinoEdgeShadowDecoration._(
      <Color>[
        for (int i = 0; i < b._colors!.length; i += 1)
855
          Color.lerp(a._colors?[i], b._colors[i], t)!,
856
      ],
857 858 859 860
    );
  }

  @override
861
  _CupertinoEdgeShadowDecoration lerpFrom(Decoration? a, double t) {
862
    if (a is _CupertinoEdgeShadowDecoration) {
863
      return _CupertinoEdgeShadowDecoration.lerp(a, this, t)!;
864
    }
865
    return _CupertinoEdgeShadowDecoration.lerp(null, this, t)!;
866 867 868
  }

  @override
869
  _CupertinoEdgeShadowDecoration lerpTo(Decoration? b, double t) {
870
    if (b is _CupertinoEdgeShadowDecoration) {
871
      return _CupertinoEdgeShadowDecoration.lerp(this, b, t)!;
872
    }
873
    return _CupertinoEdgeShadowDecoration.lerp(this, null, t)!;
874 875 876
  }

  @override
877
  _CupertinoEdgeShadowPainter createBoxPainter([ VoidCallback? onChanged ]) {
878
    return _CupertinoEdgeShadowPainter(this, onChanged);
879 880 881
  }

  @override
882
  bool operator ==(Object other) {
883
    if (other.runtimeType != runtimeType) {
884
      return false;
885
    }
886
    return other is _CupertinoEdgeShadowDecoration
887
        && other._colors == _colors;
888 889 890
  }

  @override
891
  int get hashCode => _colors.hashCode;
892 893

  @override
894 895
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
896
    properties.add(IterableProperty<Color>('colors', _colors));
897
  }
898 899 900 901 902 903
}

/// A [BoxPainter] used to draw the page transition shadow using gradients.
class _CupertinoEdgeShadowPainter extends BoxPainter {
  _CupertinoEdgeShadowPainter(
    this._decoration,
904
    super.onChanged,
905
  ) : assert(_decoration._colors == null || _decoration._colors.length > 1);
906 907 908 909 910

  final _CupertinoEdgeShadowDecoration _decoration;

  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
911 912
    final List<Color>? colors = _decoration._colors;
    if (colors == null) {
913
      return;
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
    }

    // The following code simulates drawing a [LinearGradient] configured as
    // follows:
    //
    // LinearGradient(
    //   begin: AlignmentDirectional(0.90, 0.0), // Spans 5% of the page.
    //   colors: _decoration._colors,
    // )
    //
    // A performance evaluation on Feb 8, 2021 showed, that drawing the gradient
    // manually as implemented below is more performant than relying on
    // [LinearGradient.createShader] because compiling that shader takes a long
    // time. On an iPhone XR, the implementation below reduced the worst frame
    // time for a cupertino page transition of a newly installed app from ~95ms
    // down to ~30ms, mainly because there's no longer a need to compile a
    // shader for the LinearGradient.
    //
    // The implementation below divides the width of the shadow into multiple
    // bands of equal width, one for each color interval defined by
    // `_decoration._colors`. Band x is filled with a gradient going from
    // `_decoration._colors[x]` to `_decoration._colors[x + 1]` by drawing a
    // bunch of 1px wide rects. The rects change their color by lerping between
    // the two colors that define the interval of the band.

    // Shadow spans 5% of the page.
    final double shadowWidth = 0.05 * configuration.size!.width;
    final double shadowHeight = configuration.size!.height;
    final double bandWidth = shadowWidth / (colors.length - 1);

944
    final TextDirection? textDirection = configuration.textDirection;
Ian Hickson's avatar
Ian Hickson committed
945
    assert(textDirection != null);
946 947
    final double start;
    final double shadowDirection; // -1 for ltr, 1 for rtl.
948
    switch (textDirection!) {
Ian Hickson's avatar
Ian Hickson committed
949
      case TextDirection.rtl:
950 951
        start = offset.dx + configuration.size!.width;
        shadowDirection = 1;
Ian Hickson's avatar
Ian Hickson committed
952
      case TextDirection.ltr:
953 954
        start = offset.dx;
        shadowDirection = -1;
Ian Hickson's avatar
Ian Hickson committed
955
    }
956

957 958 959 960 961 962 963 964 965 966
    int bandColorIndex = 0;
    for (int dx = 0; dx < shadowWidth; dx += 1) {
      if (dx ~/ bandWidth != bandColorIndex) {
        bandColorIndex += 1;
      }
      final Paint paint = Paint()
        ..color = Color.lerp(colors[bandColorIndex], colors[bandColorIndex + 1], (dx % bandWidth) / bandWidth)!;
      final double x = start + shadowDirection * dx;
      canvas.drawRect(Rect.fromLTWH(x - 1.0, offset.dy, 1.0, shadowHeight), paint);
    }
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
/// A route that shows a modal iOS-style popup that slides up from the
/// bottom of the screen.
///
/// Such a popup is an alternative to a menu or a dialog and prevents the user
/// from interacting with the rest of the app.
///
/// It is used internally by [showCupertinoModalPopup] or can be directly pushed
/// onto the [Navigator] stack to enable state restoration. See
/// [showCupertinoModalPopup] for a state restoration app example.
///
/// The `barrierColor` argument determines the [Color] of the barrier underneath
/// the popup. When unspecified, the barrier color defaults to a light opacity
/// black scrim based on iOS's dialog screens. To correctly have iOS resolve
/// to the appropriate modal colors, pass in
/// `CupertinoDynamicColor.resolve(kCupertinoModalBarrierColor, context)`.
///
/// The `barrierDismissible` argument determines whether clicking outside the
/// popup results in dismissal. It is `true` by default.
///
/// The `semanticsDismissible` argument is used to determine whether the
/// semantics of the modal barrier are included in the semantics tree.
///
/// The `routeSettings` argument is used to provide [RouteSettings] to the
/// created Route.
///
995 996
/// {@macro flutter.widgets.RawDialogRoute}
///
997 998
/// See also:
///
999 1000
///  * [DisplayFeatureSubScreen], which documents the specifics of how
///    [DisplayFeature]s can split the screen into sub-screens.
1001 1002 1003 1004 1005 1006 1007
///  * [CupertinoActionSheet], which is the widget usually returned by the
///    `builder` argument.
///  * <https://developer.apple.com/design/human-interface-guidelines/ios/views/action-sheets/>
class CupertinoModalPopupRoute<T> extends PopupRoute<T> {
  /// A route that shows a modal iOS-style popup that slides up from the
  /// bottom of the screen.
  CupertinoModalPopupRoute({
1008
    required this.builder,
1009 1010 1011
    this.barrierLabel = 'Dismiss',
    this.barrierColor = kCupertinoModalBarrierColor,
    bool barrierDismissible = true,
1012
    bool semanticsDismissible = false,
1013 1014
    super.filter,
    super.settings,
1015
    this.anchorPoint,
1016 1017
  }) : _barrierDismissible = barrierDismissible,
       _semanticsDismissible = semanticsDismissible;
1018

1019 1020
  /// A builder that builds the widget tree for the [CupertinoModalPopupRoute].
  ///
1021
  /// The [builder] argument typically builds a [CupertinoActionSheet] widget.
1022 1023
  ///
  /// Content below the widget is dimmed with a [ModalBarrier]. The widget built
1024
  /// by the [builder] does not share a context with the route it was originally
1025 1026
  /// built from. Use a [StatefulBuilder] or a custom [StatefulWidget] if the
  /// widget needs to update dynamically.
1027
  final WidgetBuilder builder;
1028

1029
  final bool _barrierDismissible;
1030

1031
  final bool _semanticsDismissible;
1032 1033 1034 1035 1036

  @override
  final String barrierLabel;

  @override
1037
  final Color? barrierColor;
1038 1039

  @override
1040
  bool get barrierDismissible => _barrierDismissible;
1041 1042

  @override
1043
  bool get semanticsDismissible => _semanticsDismissible;
1044 1045 1046 1047

  @override
  Duration get transitionDuration => _kModalPopupTransitionDuration;

1048
  Animation<double>? _animation;
1049

1050
  late Tween<Offset> _offsetTween;
1051

1052 1053 1054
  /// {@macro flutter.widgets.DisplayFeatureSubScreen.anchorPoint}
  final Offset? anchorPoint;

1055 1056 1057
  @override
  Animation<double> createAnimation() {
    assert(_animation == null);
1058
    _animation = CurvedAnimation(
1059
      parent: super.createAnimation(),
1060 1061 1062 1063 1064

      // These curves were initially measured from native iOS horizontal page
      // route animations and seemed to be a good match here as well.
      curve: Curves.linearToEaseOut,
      reverseCurve: Curves.linearToEaseOut.flipped,
1065
    );
1066
    _offsetTween = Tween<Offset>(
1067
      begin: const Offset(0.0, 1.0),
1068
      end: Offset.zero,
1069
    );
1070
    return _animation!;
1071 1072 1073 1074
  }

  @override
  Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
1075 1076
    return CupertinoUserInterfaceLevel(
      data: CupertinoUserInterfaceLevelData.elevated,
1077 1078 1079 1080
      child: DisplayFeatureSubScreen(
        anchorPoint: anchorPoint,
        child: Builder(builder: builder),
      ),
1081
    );
1082 1083 1084 1085
  }

  @override
  Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
1086
    return Align(
1087
      alignment: Alignment.bottomCenter,
1088
      child: FractionalTranslation(
1089
        translation: _offsetTween.evaluate(_animation!),
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
        child: child,
      ),
    );
  }
}

/// Shows a modal iOS-style popup that slides up from the bottom of the screen.
///
/// Such a popup is an alternative to a menu or a dialog and prevents the user
/// from interacting with the rest of the app.
///
/// The `context` argument is used to look up the [Navigator] for the popup.
/// It is only used when the method is called. Its corresponding widget can be
/// safely removed from the tree before the popup is closed.
///
1105 1106 1107 1108 1109 1110 1111
/// The `barrierColor` argument determines the [Color] of the barrier underneath
/// the popup. When unspecified, the barrier color defaults to a light opacity
/// black scrim based on iOS's dialog screens.
///
/// The `barrierDismissible` argument determines whether clicking outside the
/// popup results in dismissal. It is `true` by default.
///
1112 1113
/// The `useRootNavigator` argument is used to determine whether to push the
/// popup to the [Navigator] furthest from or nearest to the given `context`. It
1114
/// is `true` by default.
1115
///
1116
/// The `semanticsDismissible` argument is used to determine whether the
Dan Field's avatar
Dan Field committed
1117 1118
/// semantics of the modal barrier are included in the semantics tree.
///
1119 1120 1121
/// The `routeSettings` argument is used to provide [RouteSettings] to the
/// created Route.
///
1122 1123 1124
/// The `builder` argument typically builds a [CupertinoActionSheet] widget.
/// Content below the widget is dimmed with a [ModalBarrier]. The widget built
/// by the `builder` does not share a context with the location that
1125
/// [showCupertinoModalPopup] is originally called from. Use a
1126 1127 1128
/// [StatefulBuilder] or a custom [StatefulWidget] if the widget needs to
/// update dynamically.
///
1129 1130
/// {@macro flutter.widgets.RawDialogRoute}
///
1131 1132 1133
/// Returns a `Future` that resolves to the value that was passed to
/// [Navigator.pop] when the popup was closed.
///
1134 1135 1136 1137 1138 1139 1140 1141
/// ### State Restoration in Modals
///
/// Using this method will not enable state restoration for the modal. In order
/// to enable state restoration for a modal, use [Navigator.restorablePush]
/// or [Navigator.restorablePushNamed] with [CupertinoModalPopupRoute].
///
/// For more information about state restoration, see [RestorationManager].
///
1142
/// {@tool dartpad}
1143 1144 1145 1146 1147 1148 1149
/// This sample demonstrates how to create a restorable Cupertino modal route.
/// This is accomplished by enabling state restoration by specifying
/// [CupertinoApp.restorationScopeId] and using [Navigator.restorablePush] to
/// push [CupertinoModalPopupRoute] when the [CupertinoButton] is tapped.
///
/// {@macro flutter.widgets.RestorationManager}
///
1150
/// ** See code in examples/api/lib/cupertino/route/show_cupertino_modal_popup.0.dart **
1151 1152
/// {@end-tool}
///
1153 1154
/// See also:
///
1155 1156
///  * [DisplayFeatureSubScreen], which documents the specifics of how
///    [DisplayFeature]s can split the screen into sub-screens.
Dan Field's avatar
Dan Field committed
1157 1158
///  * [CupertinoActionSheet], which is the widget usually returned by the
///    `builder` argument to [showCupertinoModalPopup].
1159
///  * <https://developer.apple.com/design/human-interface-guidelines/ios/views/action-sheets/>
1160
Future<T?> showCupertinoModalPopup<T>({
1161 1162 1163
  required BuildContext context,
  required WidgetBuilder builder,
  ImageFilter? filter,
1164
  Color barrierColor = kCupertinoModalBarrierColor,
1165
  bool barrierDismissible = true,
1166
  bool useRootNavigator = true,
1167
  bool semanticsDismissible = false,
1168
  RouteSettings? routeSettings,
1169
  Offset? anchorPoint,
1170
}) {
1171
  return Navigator.of(context, rootNavigator: useRootNavigator).push(
1172
    CupertinoModalPopupRoute<T>(
1173 1174
      builder: builder,
      filter: filter,
1175 1176
      barrierColor: CupertinoDynamicColor.resolve(barrierColor, context),
      barrierDismissible: barrierDismissible,
Dan Field's avatar
Dan Field committed
1177
      semanticsDismissible: semanticsDismissible,
1178
      settings: routeSettings,
1179
      anchorPoint: anchorPoint,
1180 1181 1182 1183
    ),
  );
}

1184
// The curve and initial scale values were mostly eyeballed from iOS, however
1185
// they reuse the same animation curve that was modeled after native page
1186 1187 1188
// transitions.
final Animatable<double> _dialogScaleTween = Tween<double>(begin: 1.3, end: 1.0)
  .chain(CurveTween(curve: Curves.linearToEaseOut));
1189

1190
Widget _buildCupertinoDialogTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
1191
  final CurvedAnimation fadeAnimation = CurvedAnimation(
1192 1193 1194 1195
    parent: animation,
    curve: Curves.easeInOut,
  );
  if (animation.status == AnimationStatus.reverse) {
1196
    return FadeTransition(
1197 1198 1199 1200
      opacity: fadeAnimation,
      child: child,
    );
  }
1201
  return FadeTransition(
1202 1203
    opacity: fadeAnimation,
    child: ScaleTransition(
1204
      scale: animation.drive(_dialogScaleTween),
1205
      child: child,
1206 1207 1208 1209 1210 1211
    ),
  );
}

/// Displays an iOS-style dialog above the current contents of the app, with
/// iOS-style entrance and exit animations, modal barrier color, and modal
1212 1213
/// barrier behavior (by default, the dialog is not dismissible with a tap on
/// the barrier).
1214
///
1215 1216 1217
/// This function takes a `builder` which typically builds a [CupertinoAlertDialog]
/// widget. Content below the dialog is dimmed with a [ModalBarrier]. The widget
/// returned by the `builder` does not share a context with the location that
1218
/// [showCupertinoDialog] is originally called from. Use a [StatefulBuilder] or
1219
/// a custom [StatefulWidget] if the dialog needs to update dynamically.
1220 1221 1222 1223 1224
///
/// The `context` argument is used to look up the [Navigator] for the dialog.
/// It is only used when the method is called. Its corresponding widget can
/// be safely removed from the tree before the dialog is closed.
///
1225 1226 1227 1228
/// The `useRootNavigator` argument is used to determine whether to push the
/// dialog to the [Navigator] furthest from or nearest to the given `context`.
/// By default, `useRootNavigator` is `true` and the dialog route created by
/// this method is pushed to the root navigator.
1229
///
1230 1231
/// {@macro flutter.widgets.RawDialogRoute}
///
1232 1233 1234 1235
/// If the application has multiple [Navigator] objects, it may be necessary to
/// call `Navigator.of(context, rootNavigator: true).pop(result)` to close the
/// dialog rather than just `Navigator.pop(context, result)`.
///
1236 1237 1238
/// Returns a [Future] that resolves to the value (if any) that was passed to
/// [Navigator.pop] when the dialog was closed.
///
1239 1240 1241 1242 1243 1244 1245 1246
/// ### State Restoration in Dialogs
///
/// Using this method will not enable state restoration for the dialog. In order
/// to enable state restoration for a dialog, use [Navigator.restorablePush]
/// or [Navigator.restorablePushNamed] with [CupertinoDialogRoute].
///
/// For more information about state restoration, see [RestorationManager].
///
1247
/// {@tool dartpad}
1248 1249 1250 1251 1252 1253 1254
/// This sample demonstrates how to create a restorable Cupertino dialog. This is
/// accomplished by enabling state restoration by specifying
/// [CupertinoApp.restorationScopeId] and using [Navigator.restorablePush] to
/// push [CupertinoDialogRoute] when the [CupertinoButton] is tapped.
///
/// {@macro flutter.widgets.RestorationManager}
///
1255
/// ** See code in examples/api/lib/cupertino/route/show_cupertino_dialog.0.dart **
1256 1257
/// {@end-tool}
///
1258
/// See also:
1259
///
1260 1261 1262
///  * [CupertinoAlertDialog], an iOS-style alert dialog.
///  * [showDialog], which displays a Material-style dialog.
///  * [showGeneralDialog], which allows for customization of the dialog popup.
1263 1264
///  * [DisplayFeatureSubScreen], which documents the specifics of how
///    [DisplayFeature]s can split the screen into sub-screens.
1265
///  * <https://developer.apple.com/ios/human-interface-guidelines/views/alerts/>
1266
Future<T?> showCupertinoDialog<T>({
1267 1268
  required BuildContext context,
  required WidgetBuilder builder,
1269
  String? barrierLabel,
1270
  bool useRootNavigator = true,
1271
  bool barrierDismissible = false,
1272
  RouteSettings? routeSettings,
1273
  Offset? anchorPoint,
1274
}) {
1275 1276 1277

  return Navigator.of(context, rootNavigator: useRootNavigator).push<T>(CupertinoDialogRoute<T>(
    builder: builder,
1278
    context: context,
1279
    barrierDismissible: barrierDismissible,
1280
    barrierLabel: barrierLabel,
1281
    barrierColor: CupertinoDynamicColor.resolve(kCupertinoModalBarrierColor, context),
1282
    settings: routeSettings,
1283
    anchorPoint: anchorPoint,
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
  ));
}

/// A dialog route that shows an iOS-style dialog.
///
/// It is used internally by [showCupertinoDialog] or can be directly pushed
/// onto the [Navigator] stack to enable state restoration. See
/// [showCupertinoDialog] for a state restoration app example.
///
/// This function takes a `builder` which typically builds a [Dialog] widget.
/// Content below the dialog is dimmed with a [ModalBarrier]. The widget
/// returned by the `builder` does not share a context with the location that
/// `showDialog` is originally called from. Use a [StatefulBuilder] or a
/// custom [StatefulWidget] if the dialog needs to update dynamically.
///
/// The `context` argument is used to look up
/// [CupertinoLocalizations.modalBarrierDismissLabel], which provides the
/// modal with a localized accessibility label that will be used for the
/// modal's barrier. However, a custom `barrierLabel` can be passed in as well.
///
/// The `barrierDismissible` argument is used to indicate whether tapping on the
/// barrier will dismiss the dialog. It is `true` by default and cannot be `null`.
///
/// The `barrierColor` argument is used to specify the color of the modal
/// barrier that darkens everything below the dialog. If `null`, then
/// [CupertinoDynamicColor.resolve] is used to compute the modal color.
///
/// The `settings` argument define the settings for this route. See
/// [RouteSettings] for details.
///
1314 1315
/// {@macro flutter.widgets.RawDialogRoute}
///
1316 1317 1318 1319 1320 1321
/// See also:
///
///  * [showCupertinoDialog], which is a way to display
///     an iOS-style dialog.
///  * [showGeneralDialog], which allows for customization of the dialog popup.
///  * [showDialog], which displays a Material dialog.
1322 1323
///  * [DisplayFeatureSubScreen], which documents the specifics of how
///    [DisplayFeature]s can split the screen into sub-screens.
1324 1325 1326 1327 1328
class CupertinoDialogRoute<T> extends RawDialogRoute<T> {
  /// A dialog route that shows an iOS-style dialog.
  CupertinoDialogRoute({
    required WidgetBuilder builder,
    required BuildContext context,
1329
    super.barrierDismissible,
1330 1331
    Color? barrierColor,
    String? barrierLabel,
1332
    // This transition duration was eyeballed comparing with iOS
1333 1334 1335 1336
    super.transitionDuration = const Duration(milliseconds: 250),
    super.transitionBuilder = _buildCupertinoDialogTransitions,
    super.settings,
    super.anchorPoint,
1337
  }) : super(
1338 1339 1340 1341
        pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
          return builder(context);
        },
        barrierLabel: barrierLabel ?? CupertinoLocalizations.of(context).modalBarrierDismissLabel,
1342
        barrierColor: barrierColor ?? CupertinoDynamicColor.resolve(kCupertinoModalBarrierColor, context),
1343
      );
1344
}