routes.dart 82.7 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
Adam Barth's avatar
Adam Barth committed
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:async';
6
import 'dart:ui' as ui;
7

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

13
import 'actions.dart';
Adam Barth's avatar
Adam Barth committed
14
import 'basic.dart';
15
import 'display_feature_sub_screen.dart';
16 17
import 'focus_manager.dart';
import 'focus_scope.dart';
18
import 'focus_traversal.dart';
Adam Barth's avatar
Adam Barth committed
19
import 'framework.dart';
20
import 'modal_barrier.dart';
Adam Barth's avatar
Adam Barth committed
21 22
import 'navigator.dart';
import 'overlay.dart';
23
import 'page_storage.dart';
24
import 'primary_scroll_controller.dart';
25
import 'restoration.dart';
26
import 'scroll_controller.dart';
27
import 'transitions.dart';
Adam Barth's avatar
Adam Barth committed
28

29
// Examples can assume:
30
// late NavigatorState navigator;
31 32
// late BuildContext context;
// Future<bool> askTheUserIfTheyAreSure() async { return true; }
33
// abstract class MyWidget extends StatefulWidget { const MyWidget({super.key}); }
34 35
// late dynamic _myState, newValue;
// late StateSetter setState;
36

37
/// A route that displays widgets in the [Navigator]'s [Overlay].
38 39 40 41
///
/// See also:
///
///  * [Route], which documents the meaning of the `T` generic type argument.
Hixie's avatar
Hixie committed
42
abstract class OverlayRoute<T> extends Route<T> {
43 44
  /// Creates a route that knows how to interact with an [Overlay].
  OverlayRoute({
45 46
    super.settings,
  });
47

48
  /// Subclasses should override this getter to return the builders for the overlay.
49
  @factory
50
  Iterable<OverlayEntry> createOverlayEntries();
Adam Barth's avatar
Adam Barth committed
51

52
  @override
Adam Barth's avatar
Adam Barth committed
53
  List<OverlayEntry> get overlayEntries => _overlayEntries;
54
  final List<OverlayEntry> _overlayEntries = <OverlayEntry>[];
Adam Barth's avatar
Adam Barth committed
55

56
  @override
57
  void install() {
58
    assert(_overlayEntries.isEmpty);
59
    _overlayEntries.addAll(createOverlayEntries());
60
    super.install();
Adam Barth's avatar
Adam Barth committed
61 62
  }

63
  /// Controls whether [didPop] calls [NavigatorState.finalizeRoute].
64
  ///
65
  /// If true, this route removes its overlay entries during [didPop].
66 67
  /// Subclasses can override this getter if they want to delay finalization
  /// (for example to animate the route's exit before removing it from the
68
  /// overlay).
69 70 71
  ///
  /// Subclasses that return false from [finishedWhenPopped] are responsible for
  /// calling [NavigatorState.finalizeRoute] themselves.
72 73 74
  @protected
  bool get finishedWhenPopped => true;

75
  @override
76
  bool didPop(T? result) {
77 78
    final bool returnValue = super.didPop(result);
    assert(returnValue);
79
    if (finishedWhenPopped) {
80
      navigator!.finalizeRoute(this);
81
    }
82
    return returnValue;
Hixie's avatar
Hixie committed
83 84
  }

85 86
  @override
  void dispose() {
87 88 89
    for (final OverlayEntry entry in _overlayEntries) {
      entry.dispose();
    }
Adam Barth's avatar
Adam Barth committed
90
    _overlayEntries.clear();
91
    super.dispose();
92
  }
Adam Barth's avatar
Adam Barth committed
93 94
}

95
/// A route with entrance and exit transitions.
96 97 98 99
///
/// See also:
///
///  * [Route], which documents the meaning of the `T` generic type argument.
Hixie's avatar
Hixie committed
100
abstract class TransitionRoute<T> extends OverlayRoute<T> {
101 102
  /// Creates a route that animates itself when it is pushed or popped.
  TransitionRoute({
103 104
    super.settings,
  });
105

Hixie's avatar
Hixie committed
106 107
  /// This future completes only once the transition itself has finished, after
  /// the overlay entries have been removed from the navigator's overlay.
108 109
  ///
  /// This future completes once the animation has been dismissed. That will be
110 111
  /// after [popped], because [popped] typically completes before the animation
  /// even starts, as soon as the route is popped.
112 113
  Future<T?> get completed => _transitionCompleter.future;
  final Completer<T?> _transitionCompleter = Completer<T?>();
114

115 116 117 118 119 120 121 122
  /// Handle to the performance mode request.
  ///
  /// When the route is animating, the performance mode is requested. It is then
  /// disposed when the animation ends. Requesting [DartPerformanceMode.latency]
  /// indicates to the engine that the transition is latency sensitive and to delay
  /// non-essential work while this handle is active.
  PerformanceModeRequestHandle? _performanceModeRequestHandle;

123
  /// {@template flutter.widgets.TransitionRoute.transitionDuration}
124 125 126 127 128 129
  /// The duration the transition going forwards.
  ///
  /// See also:
  ///
  /// * [reverseTransitionDuration], which controls the duration of the
  /// transition when it is in reverse.
130
  /// {@endtemplate}
Adam Barth's avatar
Adam Barth committed
131
  Duration get transitionDuration;
132

133
  /// {@template flutter.widgets.TransitionRoute.reverseTransitionDuration}
134 135 136 137
  /// The duration the transition going in reverse.
  ///
  /// By default, the reverse transition duration is set to the value of
  /// the forwards [transitionDuration].
138
  /// {@endtemplate}
139 140
  Duration get reverseTransitionDuration => transitionDuration;

141
  /// {@template flutter.widgets.TransitionRoute.opaque}
142 143 144 145
  /// Whether the route obscures previous routes when the transition is complete.
  ///
  /// When an opaque route's entrance transition is complete, the routes behind
  /// the opaque route will not be built to save resources.
146
  /// {@endtemplate}
Adam Barth's avatar
Adam Barth committed
147 148
  bool get opaque;

149 150 151
  /// {@template flutter.widgets.TransitionRoute.allowSnapshotting}
  /// Whether the route transition will prefer to animate a snapshot of the
  /// entering/exiting routes.
152 153
  ///
  /// When this value is true, certain route transitions (such as the Android
154 155
  /// zoom page transition) will snapshot the entering and exiting routes.
  /// These snapshots are then animated in place of the underlying widgets to
156 157 158 159 160 161
  /// improve performance of the transition.
  ///
  /// Generally this means that animations that occur on the entering/exiting
  /// route while the route animation plays may appear frozen - unless they
  /// are a hero animation or something that is drawn in a separate overlay.
  /// {@endtemplate}
162
  bool get allowSnapshotting => true;
163

164 165 166 167
  // This ensures that if we got to the dismissed state while still current,
  // we will still be disposed when we are eventually popped.
  //
  // This situation arises when dealing with the Cupertino dismiss gesture.
168
  @override
169 170 171
  bool get finishedWhenPopped => _controller!.status == AnimationStatus.dismissed && !_popFinalized;

  bool _popFinalized = false;
172

173 174
  /// The animation that drives the route's transition and the previous route's
  /// forward transition.
175 176
  Animation<double>? get animation => _animation;
  Animation<double>? _animation;
177

178 179 180
  /// The animation controller that the route uses to drive the transitions.
  ///
  /// The animation itself is exposed by the [animation] property.
181
  @protected
182 183
  AnimationController? get controller => _controller;
  AnimationController? _controller;
184

185 186 187
  /// The animation for the route being pushed on top of this route. This
  /// animation lets this route coordinate with the entrance and exit transition
  /// of route pushed on top of this route.
188
  Animation<double>? get secondaryAnimation => _secondaryAnimation;
189 190
  final ProxyAnimation _secondaryAnimation = ProxyAnimation(kAlwaysDismissedAnimation);

191 192 193 194 195 196 197 198 199
  /// Whether to takeover the [controller] created by [createAnimationController].
  ///
  /// If true, this route will call [AnimationController.dispose] when the
  /// controller is no longer needed.
  /// If false, the controller should be disposed by whoever owned it.
  ///
  /// It defaults to `true`.
  bool willDisposeAnimationController = true;

200
  /// Called to create the animation controller that will drive the transitions to
201 202
  /// this route from the previous one, and back to the previous route from this
  /// one.
203 204 205
  ///
  /// The returned controller will be disposed by [AnimationController.dispose]
  /// if the [willDisposeAnimationController] is `true`.
206
  AnimationController createAnimationController() {
207
    assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
208
    final Duration duration = transitionDuration;
209
    final Duration reverseDuration = reverseTransitionDuration;
210
    assert(duration >= Duration.zero);
211
    return AnimationController(
212
      duration: duration,
213
      reverseDuration: reverseDuration,
214
      debugLabel: debugLabel,
215
      vsync: navigator!,
216
    );
Adam Barth's avatar
Adam Barth committed
217 218
  }

219 220
  /// Called to create the animation that exposes the current progress of
  /// the transition controlled by the animation controller created by
221
  /// [createAnimationController()].
222
  Animation<double> createAnimation() {
223
    assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
224
    assert(_controller != null);
225
    return _controller!.view;
226 227
  }

228
  T? _result;
Adam Barth's avatar
Adam Barth committed
229

230
  void _handleStatusChanged(AnimationStatus status) {
Adam Barth's avatar
Adam Barth committed
231
    switch (status) {
232
      case AnimationStatus.completed:
233
        if (overlayEntries.isNotEmpty) {
Adam Barth's avatar
Adam Barth committed
234
          overlayEntries.first.opaque = opaque;
235
        }
236 237
        _performanceModeRequestHandle?.dispose();
        _performanceModeRequestHandle = null;
238 239
      case AnimationStatus.forward:
      case AnimationStatus.reverse:
240
        if (overlayEntries.isNotEmpty) {
Adam Barth's avatar
Adam Barth committed
241
          overlayEntries.first.opaque = false;
242
        }
243 244 245
        _performanceModeRequestHandle ??=
          SchedulerBinding.instance
            .requestPerformanceMode(ui.DartPerformanceMode.latency);
246
      case AnimationStatus.dismissed:
247
        // We might still be an active route if a subclass is controlling the
Pierre-Louis's avatar
Pierre-Louis committed
248
        // transition and hits the dismissed status. For example, the iOS
249
        // back gesture drives this animation to the dismissed status before
250 251
        // removing the route and disposing it.
        if (!isActive) {
252
          navigator!.finalizeRoute(this);
253
          _popFinalized = true;
254 255
          _performanceModeRequestHandle?.dispose();
          _performanceModeRequestHandle = null;
256
        }
Adam Barth's avatar
Adam Barth committed
257 258 259
    }
  }

260
  @override
261
  void install() {
262
    assert(!_transitionCompleter.isCompleted, 'Cannot install a $runtimeType after disposing it.');
263
    _controller = createAnimationController();
264
    assert(_controller != null, '$runtimeType.createAnimationController() returned null.');
265 266
    _animation = createAnimation()
      ..addStatusListener(_handleStatusChanged);
267
    assert(_animation != null, '$runtimeType.createAnimation() returned null.');
268
    super.install();
269
    if (_animation!.isCompleted && overlayEntries.isNotEmpty) {
270 271
      overlayEntries.first.opaque = opaque;
    }
272 273
  }

274
  @override
275
  TickerFuture didPush() {
276 277
    assert(_controller != null, '$runtimeType.didPush called before calling install() or after calling dispose().');
    assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
278
    super.didPush();
279
    return _controller!.forward();
Adam Barth's avatar
Adam Barth committed
280 281
  }

282 283 284 285 286
  @override
  void didAdd() {
    assert(_controller != null, '$runtimeType.didPush called before calling install() or after calling dispose().');
    assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
    super.didAdd();
287
    _controller!.value = _controller!.upperBound;
288 289
  }

290
  @override
291
  void didReplace(Route<dynamic>? oldRoute) {
292 293
    assert(_controller != null, '$runtimeType.didReplace called before calling install() or after calling dispose().');
    assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
294
    if (oldRoute is TransitionRoute) {
295
      _controller!.value = oldRoute._controller!.value;
296
    }
297 298 299
    super.didReplace(oldRoute);
  }

300
  @override
301
  bool didPop(T? result) {
302 303
    assert(_controller != null, '$runtimeType.didPop called before calling install() or after calling dispose().');
    assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
Adam Barth's avatar
Adam Barth committed
304
    _result = result;
305
    _controller!.reverse();
306
    return super.didPop(result);
Hixie's avatar
Hixie committed
307 308
  }

309
  @override
310
  void didPopNext(Route<dynamic> nextRoute) {
311 312
    assert(_controller != null, '$runtimeType.didPopNext called before calling install() or after calling dispose().');
    assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
313
    _updateSecondaryAnimation(nextRoute);
Hixie's avatar
Hixie committed
314
    super.didPopNext(nextRoute);
Adam Barth's avatar
Adam Barth committed
315 316
  }

317
  @override
318
  void didChangeNext(Route<dynamic>? nextRoute) {
319 320
    assert(_controller != null, '$runtimeType.didChangeNext called before calling install() or after calling dispose().');
    assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
321
    _updateSecondaryAnimation(nextRoute);
Hixie's avatar
Hixie committed
322
    super.didChangeNext(nextRoute);
323 324
  }

325 326 327 328 329
  // A callback method that disposes existing train hopping animation and
  // removes its listener.
  //
  // This property is non-null if there is a train hopping in progress, and the
  // caller must reset this property to null after it is called.
330
  VoidCallback? _trainHoppingListenerRemover;
331

332
  void _updateSecondaryAnimation(Route<dynamic>? nextRoute) {
333 334 335
    // There is an existing train hopping in progress. Unfortunately, we cannot
    // dispose current train hopping animation until we replace it with a new
    // animation.
336
    final VoidCallback? previousTrainHoppingListenerRemover = _trainHoppingListenerRemover;
337 338
    _trainHoppingListenerRemover = null;

339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
    if (nextRoute is TransitionRoute<dynamic> && canTransitionTo(nextRoute) && nextRoute.canTransitionFrom(this)) {
      final Animation<double>? current = _secondaryAnimation.parent;
      if (current != null) {
        final Animation<double> currentTrain = (current is TrainHoppingAnimation ? current.currentTrain : current)!;
        final Animation<double> nextTrain = nextRoute._animation!;
        if (
          currentTrain.value == nextTrain.value ||
          nextTrain.status == AnimationStatus.completed ||
          nextTrain.status == AnimationStatus.dismissed
        ) {
          _setSecondaryAnimation(nextTrain, nextRoute.completed);
        } else {
          // Two trains animate at different values. We have to do train hopping.
          // There are three possibilities of train hopping:
          //  1. We hop on the nextTrain when two trains meet in the middle using
          //     TrainHoppingAnimation.
          //  2. There is no chance to hop on nextTrain because two trains never
          //     cross each other. We have to directly set the animation to
          //     nextTrain once the nextTrain stops animating.
          //  3. A new _updateSecondaryAnimation is called before train hopping
          //     finishes. We leave a listener remover for the next call to
          //     properly clean up the existing train hopping.
          TrainHoppingAnimation? newAnimation;
          void jumpOnAnimationEnd(AnimationStatus status) {
            switch (status) {
              case AnimationStatus.completed:
              case AnimationStatus.dismissed:
                // The nextTrain has stopped animating without train hopping.
                // Directly sets the secondary animation and disposes the
                // TrainHoppingAnimation.
                _setSecondaryAnimation(nextTrain, nextRoute.completed);
370
                if (_trainHoppingListenerRemover != null) {
371
                  _trainHoppingListenerRemover!();
372 373
                  _trainHoppingListenerRemover = null;
                }
374 375 376 377
              case AnimationStatus.forward:
              case AnimationStatus.reverse:
                break;
            }
378
          }
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
          _trainHoppingListenerRemover = () {
            nextTrain.removeStatusListener(jumpOnAnimationEnd);
            newAnimation?.dispose();
          };
          nextTrain.addStatusListener(jumpOnAnimationEnd);
          newAnimation = TrainHoppingAnimation(
            currentTrain,
            nextTrain,
            onSwitchedTrain: () {
              assert(_secondaryAnimation.parent == newAnimation);
              assert(newAnimation!.currentTrain == nextRoute._animation);
              // We can hop on the nextTrain, so we don't need to listen to
              // whether the nextTrain has stopped.
              _setSecondaryAnimation(newAnimation!.currentTrain, nextRoute.completed);
              if (_trainHoppingListenerRemover != null) {
                _trainHoppingListenerRemover!();
                _trainHoppingListenerRemover = null;
              }
            },
          );
          _setSecondaryAnimation(newAnimation, nextRoute.completed);
400
        }
Hixie's avatar
Hixie committed
401
      } else {
402
        _setSecondaryAnimation(nextRoute._animation, nextRoute.completed);
Hixie's avatar
Hixie committed
403
      }
404
    } else {
405
      _setSecondaryAnimation(kAlwaysDismissedAnimation);
Hixie's avatar
Hixie committed
406
    }
407 408 409 410 411
    // Finally, we dispose any previous train hopping animation because it
    // has been successfully updated at this point.
    if (previousTrainHoppingListenerRemover != null) {
      previousTrainHoppingListenerRemover();
    }
Hixie's avatar
Hixie committed
412 413
  }

414
  void _setSecondaryAnimation(Animation<double>? animation, [Future<dynamic>? disposed]) {
415
    _secondaryAnimation.parent = animation;
416
    // Releases the reference to the next route's animation when that route
417
    // is disposed.
418
    disposed?.then((dynamic _) {
419 420 421 422 423 424 425 426 427
      if (_secondaryAnimation.parent == animation) {
        _secondaryAnimation.parent = kAlwaysDismissedAnimation;
        if (animation is TrainHoppingAnimation) {
          animation.dispose();
        }
      }
    });
  }

428 429 430
  /// Returns true if this route supports a transition animation that runs
  /// when [nextRoute] is pushed on top of it or when [nextRoute] is popped
  /// off of it.
431
  ///
432
  /// Subclasses can override this method to restrict the set of routes they
433
  /// need to coordinate transitions with.
434 435
  ///
  /// If true, and `nextRoute.canTransitionFrom()` is true, then the
436
  /// [ModalRoute.buildTransitions] `secondaryAnimation` will run from 0.0 - 1.0
437
  /// when [nextRoute] is pushed on top of this one. Similarly, if
438 439 440
  /// the [nextRoute] is popped off of this route, the
  /// `secondaryAnimation` will run from 1.0 - 0.0.
  ///
441 442 443
  /// If false, this route's [ModalRoute.buildTransitions] `secondaryAnimation` parameter
  /// value will be [kAlwaysDismissedAnimation]. In other words, this route
  /// will not animate when [nextRoute] is pushed on top of it or when
444 445 446 447 448 449 450
  /// [nextRoute] is popped off of it.
  ///
  /// Returns true by default.
  ///
  /// See also:
  ///
  ///  * [canTransitionFrom], which must be true for [nextRoute] for the
451
  ///    [ModalRoute.buildTransitions] `secondaryAnimation` to run.
452
  bool canTransitionTo(TransitionRoute<dynamic> nextRoute) => true;
453

454 455
  /// Returns true if [previousRoute] should animate when this route
  /// is pushed on top of it or when then this route is popped off of it.
456
  ///
457
  /// Subclasses can override this method to restrict the set of routes they
458
  /// need to coordinate transitions with.
459 460
  ///
  /// If true, and `previousRoute.canTransitionTo()` is true, then the
461
  /// previous route's [ModalRoute.buildTransitions] `secondaryAnimation` will
462 463 464 465
  /// run from 0.0 - 1.0 when this route is pushed on top of
  /// it. Similarly, if this route is popped off of [previousRoute]
  /// the previous route's `secondaryAnimation` will run from 1.0 - 0.0.
  ///
466
  /// If false, then the previous route's [ModalRoute.buildTransitions]
467 468 469 470 471 472 473 474 475
  /// `secondaryAnimation` value will be kAlwaysDismissedAnimation. In
  /// other words [previousRoute] will not animate when this route is
  /// pushed on top of it or when then this route is popped off of it.
  ///
  /// Returns true by default.
  ///
  /// See also:
  ///
  ///  * [canTransitionTo], which must be true for [previousRoute] for its
476
  ///    [ModalRoute.buildTransitions] `secondaryAnimation` to run.
477
  bool canTransitionFrom(TransitionRoute<dynamic> previousRoute) => true;
478

479
  @override
Hixie's avatar
Hixie committed
480
  void dispose() {
481
    assert(!_transitionCompleter.isCompleted, 'Cannot dispose a $runtimeType twice.');
482
    _animation?.removeStatusListener(_handleStatusChanged);
483 484
    _performanceModeRequestHandle?.dispose();
    _performanceModeRequestHandle = null;
485 486 487
    if (willDisposeAnimationController) {
      _controller?.dispose();
    }
488
    _transitionCompleter.complete(_result);
Hixie's avatar
Hixie committed
489 490 491
    super.dispose();
  }

492
  /// A short description of this route useful for debugging.
493
  String get debugLabel => objectRuntimeType(this, 'TransitionRoute');
494 495

  @override
496
  String toString() => '${objectRuntimeType(this, 'TransitionRoute')}(animation: $_controller)';
Adam Barth's avatar
Adam Barth committed
497
}
498

499
/// An entry in the history of a [LocalHistoryRoute].
Hixie's avatar
Hixie committed
500
class LocalHistoryEntry {
501
  /// Creates an entry in the history of a [LocalHistoryRoute].
502 503 504
  ///
  /// The [impliesAppBarDismissal] defaults to true if not provided.
  LocalHistoryEntry({ this.onRemove, this.impliesAppBarDismissal = true });
505 506

  /// Called when this entry is removed from the history of its associated [LocalHistoryRoute].
507
  final VoidCallback? onRemove;
508

509
  LocalHistoryRoute<dynamic>? _owner;
510

511 512 513 514 515 516
  /// Whether an [AppBar] in the route this entry belongs to should
  /// automatically add a back button or close button.
  ///
  /// Defaults to true.
  final bool impliesAppBarDismissal;

517
  /// Remove this entry from the history of its associated [LocalHistoryRoute].
Hixie's avatar
Hixie committed
518
  void remove() {
519
    _owner?.removeLocalHistoryEntry(this);
520
    assert(_owner == null);
Hixie's avatar
Hixie committed
521
  }
522

Hixie's avatar
Hixie committed
523
  void _notifyRemoved() {
524
    onRemove?.call();
Hixie's avatar
Hixie committed
525 526 527
  }
}

528
/// A mixin used by routes to handle back navigations internally by popping a list.
529 530
///
/// When a [Navigator] is instructed to pop, the current route is given an
531
/// opportunity to handle the pop internally. A [LocalHistoryRoute] handles the
532 533
/// pop internally if its list of local history entries is non-empty. Rather
/// than being removed as the current route, the most recent [LocalHistoryEntry]
534
/// is removed from the list and its [LocalHistoryEntry.onRemove] is called.
535 536 537 538
///
/// See also:
///
///  * [Route], which documents the meaning of the `T` generic type argument.
539
mixin LocalHistoryRoute<T> on Route<T> {
540
  List<LocalHistoryEntry>? _localHistory;
541
  int _entriesImpliesAppBarDismissal = 0;
542 543
  /// Adds a local history entry to this route.
  ///
544
  /// When asked to pop, if this route has any local history entries, this route
545 546 547 548 549
  /// will handle the pop internally by removing the most recently added local
  /// history entry.
  ///
  /// The given local history entry must not already be part of another local
  /// history route.
550
  ///
551
  /// {@tool snippet}
552 553 554 555 556 557 558 559 560 561 562 563 564 565
  ///
  /// The following example is an app with 2 pages: `HomePage` and `SecondPage`.
  /// The `HomePage` can navigate to the `SecondPage`.
  ///
  /// The `SecondPage` uses a [LocalHistoryEntry] to implement local navigation
  /// within that page. Pressing 'show rectangle' displays a red rectangle and
  /// adds a local history entry. At that point, pressing the '< back' button
  /// pops the latest route, which is the local history entry, and the red
  /// rectangle disappears. Pressing the '< back' button a second time
  /// once again pops the latest route, which is the `SecondPage`, itself.
  /// Therefore, the second press navigates back to the `HomePage`.
  ///
  /// ```dart
  /// class App extends StatelessWidget {
566
  ///   const App({super.key});
567
  ///
568 569
  ///   @override
  ///   Widget build(BuildContext context) {
570
  ///     return MaterialApp(
571
  ///       initialRoute: '/',
572 573 574
  ///       routes: <String, WidgetBuilder>{
  ///         '/': (BuildContext context) => const HomePage(),
  ///         '/second_page': (BuildContext context) => const SecondPage(),
575 576 577 578 579 580
  ///       },
  ///     );
  ///   }
  /// }
  ///
  /// class HomePage extends StatefulWidget {
581
  ///   const HomePage({super.key});
582 583
  ///
  ///   @override
584
  ///   State<HomePage> createState() => _HomePageState();
585 586 587 588 589
  /// }
  ///
  /// class _HomePageState extends State<HomePage> {
  ///   @override
  ///   Widget build(BuildContext context) {
590 591
  ///     return Scaffold(
  ///       body: Center(
592 593 594
  ///         child: Column(
  ///           mainAxisSize: MainAxisSize.min,
  ///           children: <Widget>[
595
  ///             const Text('HomePage'),
596
  ///             // Press this button to open the SecondPage.
597
  ///             ElevatedButton(
598
  ///               child: const Text('Second Page >'),
599 600 601 602 603 604 605 606 607 608 609 610
  ///               onPressed: () {
  ///                 Navigator.pushNamed(context, '/second_page');
  ///               },
  ///             ),
  ///           ],
  ///         ),
  ///       ),
  ///     );
  ///   }
  /// }
  ///
  /// class SecondPage extends StatefulWidget {
611
  ///   const SecondPage({super.key});
612
  ///
613
  ///   @override
614
  ///   State<SecondPage> createState() => _SecondPageState();
615 616 617 618 619 620
  /// }
  ///
  /// class _SecondPageState extends State<SecondPage> {
  ///
  ///   bool _showRectangle = false;
  ///
621
  ///   Future<void> _navigateLocallyToShowRectangle() async {
622 623 624 625
  ///     // This local history entry essentially represents the display of the red
  ///     // rectangle. When this local history entry is removed, we hide the red
  ///     // rectangle.
  ///     setState(() => _showRectangle = true);
626
  ///     ModalRoute.of(context)?.addLocalHistoryEntry(
627
  ///         LocalHistoryEntry(
628 629 630 631 632 633 634 635 636 637
  ///             onRemove: () {
  ///               // Hide the red rectangle.
  ///               setState(() => _showRectangle = false);
  ///             }
  ///         )
  ///     );
  ///   }
  ///
  ///   @override
  ///   Widget build(BuildContext context) {
638
  ///     final Widget localNavContent = _showRectangle
639
  ///       ? Container(
640 641 642 643
  ///           width: 100.0,
  ///           height: 100.0,
  ///           color: Colors.red,
  ///         )
644
  ///       : ElevatedButton(
645
  ///           onPressed: _navigateLocallyToShowRectangle,
646
  ///           child: const Text('Show Rectangle'),
647 648
  ///         );
  ///
649
  ///     return Scaffold(
650
  ///       body: Center(
651
  ///         child: Column(
652 653 654
  ///           mainAxisAlignment: MainAxisAlignment.center,
  ///           children: <Widget>[
  ///             localNavContent,
655
  ///             ElevatedButton(
656
  ///               child: const Text('< Back'),
657 658
  ///               onPressed: () {
  ///                 // Pop a route. If this is pressed while the red rectangle is
nt4f04uNd's avatar
nt4f04uNd committed
659
  ///                 // visible then it will pop our local history entry, which
660 661 662 663 664 665 666 667 668 669 670 671
  ///                 // will hide the red rectangle. Otherwise, the SecondPage will
  ///                 // navigate back to the HomePage.
  ///                 Navigator.of(context).pop();
  ///               },
  ///             ),
  ///           ],
  ///         ),
  ///       ),
  ///     );
  ///   }
  /// }
  /// ```
672
  /// {@end-tool}
Hixie's avatar
Hixie committed
673 674 675 676
  void addLocalHistoryEntry(LocalHistoryEntry entry) {
    assert(entry._owner == null);
    entry._owner = this;
    _localHistory ??= <LocalHistoryEntry>[];
677 678
    final bool wasEmpty = _localHistory!.isEmpty;
    _localHistory!.add(entry);
679 680 681 682 683
    bool internalStateChanged = false;
    if (entry.impliesAppBarDismissal) {
      internalStateChanged = _entriesImpliesAppBarDismissal == 0;
      _entriesImpliesAppBarDismissal += 1;
    }
684
    if (wasEmpty || internalStateChanged) {
685
      changedInternalState();
686
    }
Hixie's avatar
Hixie committed
687
  }
688 689 690

  /// Remove a local history entry from this route.
  ///
691 692
  /// The entry's [LocalHistoryEntry.onRemove] callback, if any, will be called
  /// synchronously.
Hixie's avatar
Hixie committed
693 694
  void removeLocalHistoryEntry(LocalHistoryEntry entry) {
    assert(entry._owner == this);
695
    assert(_localHistory!.contains(entry));
696 697 698 699 700
    bool internalStateChanged = false;
    if (_localHistory!.remove(entry) && entry.impliesAppBarDismissal) {
      _entriesImpliesAppBarDismissal -= 1;
      internalStateChanged = _entriesImpliesAppBarDismissal == 0;
    }
Hixie's avatar
Hixie committed
701 702
    entry._owner = null;
    entry._notifyRemoved();
703 704
    if (_localHistory!.isEmpty || internalStateChanged) {
      assert(_entriesImpliesAppBarDismissal == 0);
705
      if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) {
706 707 708
        // The local history might be removed as a result of disposing inactive
        // elements during finalizeTree. The state is locked at this moment, and
        // we can only notify state has changed in the next frame.
709
        SchedulerBinding.instance.addPostFrameCallback((Duration duration) {
710 711 712
          if (isActive) {
            changedInternalState();
          }
713 714 715 716 717
        });
      } else {
        changedInternalState();
      }
    }
Hixie's avatar
Hixie committed
718
  }
719

720
  @override
721
  Future<RoutePopDisposition> willPop() async {
722
    if (willHandlePopInternally) {
723
      return RoutePopDisposition.pop;
724
    }
725
    return super.willPop();
726 727
  }

728
  @override
729
  bool didPop(T? result) {
730 731
    if (_localHistory != null && _localHistory!.isNotEmpty) {
      final LocalHistoryEntry entry = _localHistory!.removeLast();
Hixie's avatar
Hixie committed
732 733 734
      assert(entry._owner == this);
      entry._owner = null;
      entry._notifyRemoved();
735 736 737 738 739
      bool internalStateChanged = false;
      if (entry.impliesAppBarDismissal) {
        _entriesImpliesAppBarDismissal -= 1;
        internalStateChanged = _entriesImpliesAppBarDismissal == 0;
      }
740
      if (_localHistory!.isEmpty || internalStateChanged) {
741
        changedInternalState();
742
      }
Hixie's avatar
Hixie committed
743 744 745 746
      return false;
    }
    return super.didPop(result);
  }
747 748

  @override
Hixie's avatar
Hixie committed
749
  bool get willHandlePopInternally {
750
    return _localHistory != null && _localHistory!.isNotEmpty;
Hixie's avatar
Hixie committed
751
  }
Hixie's avatar
Hixie committed
752 753
}

754
class _DismissModalAction extends DismissAction {
755 756 757 758 759 760
  _DismissModalAction(this.context);

  final BuildContext context;

  @override
  bool isEnabled(DismissIntent intent) {
761
    final ModalRoute<dynamic> route = ModalRoute.of<dynamic>(context)!;
762 763 764
    return route.barrierDismissible;
  }

765 766
  @override
  Object invoke(DismissIntent intent) {
767
    return Navigator.of(context).maybePop();
768 769 770
  }
}

Hixie's avatar
Hixie committed
771
class _ModalScopeStatus extends InheritedWidget {
772
  const _ModalScopeStatus({
773 774
    required this.isCurrent,
    required this.canPop,
775
    required this.impliesAppBarDismissal,
776
    required this.route,
777
    required super.child,
778
  });
Hixie's avatar
Hixie committed
779

780
  final bool isCurrent;
781
  final bool canPop;
782
  final bool impliesAppBarDismissal;
783
  final Route<dynamic> route;
Hixie's avatar
Hixie committed
784

785
  @override
Hixie's avatar
Hixie committed
786
  bool updateShouldNotify(_ModalScopeStatus old) {
787
    return isCurrent != old.isCurrent ||
788
           canPop != old.canPop ||
789
           impliesAppBarDismissal != old.impliesAppBarDismissal ||
Hixie's avatar
Hixie committed
790 791 792
           route != old.route;
  }

793
  @override
794
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
795
    super.debugFillProperties(description);
796 797
    description.add(FlagProperty('isCurrent', value: isCurrent, ifTrue: 'active', ifFalse: 'inactive'));
    description.add(FlagProperty('canPop', value: canPop, ifTrue: 'can pop'));
798
    description.add(FlagProperty('impliesAppBarDismissal', value: impliesAppBarDismissal, ifTrue: 'implies app bar dismissal'));
Hixie's avatar
Hixie committed
799 800 801
  }
}

802
class _ModalScope<T> extends StatefulWidget {
803
  const _ModalScope({
804
    super.key,
805
    required this.route,
806
  });
807

808
  final ModalRoute<T> route;
809

810
  @override
811
  _ModalScopeState<T> createState() => _ModalScopeState<T>();
812 813
}

814 815 816 817 818
class _ModalScopeState<T> extends State<_ModalScope<T>> {
  // We cache the result of calling the route's buildPage, and clear the cache
  // whenever the dependencies change. This implements the contract described in
  // the documentation for buildPage, namely that it gets called once, unless
  // something like a ModalRoute.of() dependency triggers an update.
819
  Widget? _page;
820 821

  // This is the combination of the two animations for the route.
822
  late Listenable _listenable;
823

824 825
  /// The node this scope will use for its root [FocusScope] widget.
  final FocusScopeNode focusScopeNode = FocusScopeNode(debugLabel: '$_ModalScopeState Focus Scope');
826
  final ScrollController primaryScrollController = ScrollController();
827

828
  @override
829 830
  void initState() {
    super.initState();
831
    final List<Listenable> animations = <Listenable>[
832 833
      if (widget.route.animation != null) widget.route.animation!,
      if (widget.route.secondaryAnimation != null) widget.route.secondaryAnimation!,
834
    ];
835
    _listenable = Listenable.merge(animations);
836 837
  }

838
  @override
839
  void didUpdateWidget(_ModalScope<T> oldWidget) {
840
    super.didUpdateWidget(oldWidget);
841
    assert(widget.route == oldWidget.route);
842
    _updateFocusScopeNode();
843 844
  }

845
  @override
846 847 848
  void didChangeDependencies() {
    super.didChangeDependencies();
    _page = null;
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
    _updateFocusScopeNode();
  }

  void _updateFocusScopeNode() {
    final TraversalEdgeBehavior traversalEdgeBehavior;
    final ModalRoute<T> route = widget.route;
    if (route.traversalEdgeBehavior != null) {
      traversalEdgeBehavior = route.traversalEdgeBehavior!;
    } else {
      traversalEdgeBehavior = route.navigator!.widget.routeTraversalEdgeBehavior;
    }
    focusScopeNode.traversalEdgeBehavior = traversalEdgeBehavior;
    if (route.isCurrent && _shouldRequestFocus) {
      route.navigator!.focusNode.enclosingScope?.setFirstFocus(focusScopeNode);
    }
864 865
  }

866
  void _forceRebuildPage() {
867
    setState(() {
868
      _page = null;
869 870 871
    });
  }

872 873 874 875 876 877
  @override
  void dispose() {
    focusScopeNode.dispose();
    super.dispose();
  }

878 879 880 881 882
  bool get _shouldIgnoreFocusRequest {
    return widget.route.animation?.status == AnimationStatus.reverse ||
      (widget.route.navigator?.userGestureInProgress ?? false);
  }

883 884 885 886
  bool get _shouldRequestFocus {
    return widget.route.navigator!.widget.requestFocus;
  }

887 888
  // This should be called to wrap any changes to route.isCurrent, route.canPop,
  // and route.offstage.
889
  void _routeSetState(VoidCallback fn) {
890
    if (widget.route.isCurrent && !_shouldIgnoreFocusRequest && _shouldRequestFocus) {
891
      widget.route.navigator!.focusNode.enclosingScope?.setFirstFocus(focusScopeNode);
892
    }
893
    setState(fn);
894 895
  }

896
  @override
897
  Widget build(BuildContext context) {
898 899 900 901 902 903 904 905 906 907 908 909 910
    return AnimatedBuilder(
      animation: widget.route.restorationScopeId,
      builder: (BuildContext context, Widget? child) {
        assert(child != null);
        return RestorationScope(
          restorationId: widget.route.restorationScopeId.value,
          child: child!,
        );
      },
      child: _ModalScopeStatus(
        route: widget.route,
        isCurrent: widget.route.isCurrent, // _routeSetState is called if this updates
        canPop: widget.route.canPop, // _routeSetState is called if this updates
911
        impliesAppBarDismissal: widget.route.impliesAppBarDismissal,
912 913 914 915
        child: Offstage(
          offstage: widget.route.offstage, // _routeSetState is called if this updates
          child: PageStorage(
            bucket: widget.route._storageBucket, // immutable
916 917 918 919 920 921
            child: Builder(
              builder: (BuildContext context) {
                return Actions(
                  actions: <Type, Action<Intent>>{
                    DismissIntent: _DismissModalAction(context),
                  },
922 923 924 925
                  child: PrimaryScrollController(
                    controller: primaryScrollController,
                    child: FocusScope(
                      node: focusScopeNode, // immutable
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
                      child: RepaintBoundary(
                        child: AnimatedBuilder(
                          animation: _listenable, // immutable
                          builder: (BuildContext context, Widget? child) {
                            return widget.route.buildTransitions(
                              context,
                              widget.route.animation!,
                              widget.route.secondaryAnimation!,
                              // This additional AnimatedBuilder is include because if the
                              // value of the userGestureInProgressNotifier changes, it's
                              // only necessary to rebuild the IgnorePointer widget and set
                              // the focus node's ability to focus.
                              AnimatedBuilder(
                                animation: widget.route.navigator?.userGestureInProgressNotifier ?? ValueNotifier<bool>(false),
                                builder: (BuildContext context, Widget? child) {
                                  final bool ignoreEvents = _shouldIgnoreFocusRequest;
                                  focusScopeNode.canRequestFocus = !ignoreEvents;
                                  return IgnorePointer(
                                    ignoring: ignoreEvents,
                                    child: child,
946 947
                                  );
                                },
948
                                child: child,
949
                              ),
950 951 952 953 954 955 956 957 958 959 960 961
                            );
                          },
                          child: _page ??= RepaintBoundary(
                            key: widget.route._subtreeKey, // immutable
                            child: Builder(
                              builder: (BuildContext context) {
                                return widget.route.buildPage(
                                  context,
                                  widget.route.animation!,
                                  widget.route.secondaryAnimation!,
                                );
                              },
962 963 964
                            ),
                          ),
                        ),
965
                      ),
966
                    ),
967
                  ),
968 969
                );
              },
970 971 972 973
            ),
          ),
        ),
      ),
974
    );
975 976 977
  }
}

978
/// A route that blocks interaction with previous routes.
979
///
980 981 982 983 984 985
/// [ModalRoute]s cover the entire [Navigator]. They are not necessarily
/// [opaque], however; for example, a pop-up menu uses a [ModalRoute] but only
/// shows the menu in a small box overlapping the previous route.
///
/// The `T` type argument is the return value of the route. If there is no
/// return value, consider using `void` as the return value.
986 987 988 989
///
/// See also:
///
///  * [Route], which further documents the meaning of the `T` generic type argument.
990
abstract class ModalRoute<T> extends TransitionRoute<T> with LocalHistoryRoute<T> {
991
  /// Creates a route that blocks interaction with previous routes.
992
  ModalRoute({
993
    super.settings,
994
    this.filter,
995
    this.traversalEdgeBehavior,
996
  });
997 998 999 1000 1001

  /// The filter to add to the barrier.
  ///
  /// If given, this filter will be applied to the modal barrier using
  /// [BackdropFilter]. This allows blur effects, for example.
1002
  final ui.ImageFilter? filter;
1003

1004 1005 1006 1007 1008 1009
  /// Controls the transfer of focus beyond the first and the last items of a
  /// [FocusScopeNode].
  ///
  /// If set to null, [Navigator.routeTraversalEdgeBehavior] is used.
  final TraversalEdgeBehavior? traversalEdgeBehavior;

Hixie's avatar
Hixie committed
1010 1011
  // The API for general users of this class

1012 1013
  /// Returns the modal route most closely associated with the given context.
  ///
1014
  /// Returns null if the given context is not associated with a modal route.
1015
  ///
1016 1017
  /// {@tool snippet}
  ///
1018 1019 1020
  /// Typical usage is as follows:
  ///
  /// ```dart
1021
  /// ModalRoute<int>? route = ModalRoute.of<int>(context);
1022
  /// ```
1023
  /// {@end-tool}
1024 1025
  ///
  /// The given [BuildContext] will be rebuilt if the state of the route changes
1026
  /// while it is visible (specifically, if [isCurrent] or [canPop] change value).
1027
  @optionalTypeArgs
1028
  static ModalRoute<T>? of<T extends Object?>(BuildContext context) {
1029 1030
    final _ModalScopeStatus? widget = context.dependOnInheritedWidgetOfExactType<_ModalScopeStatus>();
    return widget?.route as ModalRoute<T>?;
Hixie's avatar
Hixie committed
1031 1032
  }

1033 1034
  /// Schedule a call to [buildTransitions].
  ///
1035
  /// Whenever you need to change internal state for a [ModalRoute] object, make
1036
  /// the change in a function that you pass to [setState], as in:
1037 1038
  ///
  /// ```dart
1039
  /// setState(() { _myState = newValue; });
1040 1041
  /// ```
  ///
1042
  /// If you just change the state directly without calling [setState], then the
1043 1044 1045 1046 1047
  /// route will not be scheduled for rebuilding, meaning that its rendering
  /// will not be updated.
  @protected
  void setState(VoidCallback fn) {
    if (_scopeKey.currentState != null) {
1048
      _scopeKey.currentState!._routeSetState(fn);
1049 1050 1051 1052 1053 1054 1055 1056
    } else {
      // The route isn't currently visible, so we don't have to call its setState
      // method, but we do still need to call the fn callback, otherwise the state
      // in the route won't be updated!
      fn();
    }
  }

Hans Muller's avatar
Hans Muller committed
1057 1058 1059 1060 1061 1062
  /// Returns a predicate that's true if the route has the specified name and if
  /// popping the route will not yield the same route, i.e. if the route's
  /// [willHandlePopInternally] property is false.
  ///
  /// This function is typically used with [Navigator.popUntil()].
  static RoutePredicate withName(String name) {
1063
    return (Route<dynamic> route) {
Hans Muller's avatar
Hans Muller committed
1064
      return !route.willHandlePopInternally
1065 1066
          && route is ModalRoute
          && route.settings.name == name;
Hans Muller's avatar
Hans Muller committed
1067 1068
    };
  }
1069 1070 1071

  // The API for subclasses to override - used by _ModalScope

1072
  /// Override this method to build the primary content of this route.
1073
  ///
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
  /// The arguments have the following meanings:
  ///
  ///  * `context`: The context in which the route is being built.
  ///  * [animation]: The animation for this route's transition. When entering,
  ///    the animation runs forward from 0.0 to 1.0. When exiting, this animation
  ///    runs backwards from 1.0 to 0.0.
  ///  * [secondaryAnimation]: The animation for the route being pushed on top of
  ///    this route. This animation lets this route coordinate with the entrance
  ///    and exit transition of routes pushed on top of this route.
  ///
1084 1085 1086 1087 1088 1089 1090 1091
  /// This method is only called when the route is first built, and rarely
  /// thereafter. In particular, it is not automatically called again when the
  /// route's state changes unless it uses [ModalRoute.of]. For a builder that
  /// is called every time the route's state changes, consider
  /// [buildTransitions]. For widgets that change their behavior when the
  /// route's state changes, consider [ModalRoute.of] to obtain a reference to
  /// the route; this will cause the widget to be rebuilt each time the route
  /// changes state.
1092 1093 1094 1095 1096
  ///
  /// In general, [buildPage] should be used to build the page contents, and
  /// [buildTransitions] for the widgets that change as the page is brought in
  /// and out of view. Avoid using [buildTransitions] for content that never
  /// changes; building such content once from [buildPage] is more efficient.
1097
  Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation);
1098

1099 1100
  /// Override this method to wrap the [child] with one or more transition
  /// widgets that define how the route arrives on and leaves the screen.
1101
  ///
1102 1103 1104 1105
  /// By default, the child (which contains the widget returned by [buildPage])
  /// is not wrapped in any transition widgets.
  ///
  /// The [buildTransitions] method, in contrast to [buildPage], is called each
1106 1107
  /// time the [Route]'s state changes while it is visible (e.g. if the value of
  /// [canPop] changes on the active route).
1108
  ///
1109
  /// The [buildTransitions] method is typically used to define transitions
1110 1111 1112 1113 1114 1115
  /// that animate the new topmost route's comings and goings. When the
  /// [Navigator] pushes a route on the top of its stack, the new route's
  /// primary [animation] runs from 0.0 to 1.0. When the Navigator pops the
  /// topmost route, e.g. because the use pressed the back button, the
  /// primary animation runs from 1.0 to 0.0.
  ///
1116
  /// {@tool snippet}
1117 1118 1119 1120 1121 1122
  /// The following example uses the primary animation to drive a
  /// [SlideTransition] that translates the top of the new route vertically
  /// from the bottom of the screen when it is pushed on the Navigator's
  /// stack. When the route is popped the SlideTransition translates the
  /// route from the top of the screen back to the bottom.
  ///
1123 1124 1125 1126
  /// We've used [PageRouteBuilder] to demonstrate the [buildTransitions] method
  /// here. The body of an override of the [buildTransitions] method would be
  /// defined in the same way.
  ///
1127
  /// ```dart
1128
  /// PageRouteBuilder<void>(
1129 1130 1131 1132
  ///   pageBuilder: (BuildContext context,
  ///       Animation<double> animation,
  ///       Animation<double> secondaryAnimation,
  ///   ) {
1133
  ///     return Scaffold(
1134 1135
  ///       appBar: AppBar(title: const Text('Hello')),
  ///       body: const Center(
1136
  ///         child: Text('Hello World'),
1137 1138 1139 1140 1141 1142 1143 1144 1145
  ///       ),
  ///     );
  ///   },
  ///   transitionsBuilder: (
  ///       BuildContext context,
  ///       Animation<double> animation,
  ///       Animation<double> secondaryAnimation,
  ///       Widget child,
  ///    ) {
1146 1147
  ///     return SlideTransition(
  ///       position: Tween<Offset>(
1148 1149
  ///         begin: const Offset(0.0, 1.0),
  ///         end: Offset.zero,
1150 1151 1152 1153
  ///       ).animate(animation),
  ///       child: child, // child is the value returned by pageBuilder
  ///     );
  ///   },
1154
  /// )
1155
  /// ```
1156
  /// {@end-tool}
1157
  ///
1158
  /// When the [Navigator] pushes a route on the top of its stack, the
1159 1160 1161 1162 1163
  /// [secondaryAnimation] can be used to define how the route that was on
  /// the top of the stack leaves the screen. Similarly when the topmost route
  /// is popped, the secondaryAnimation can be used to define how the route
  /// below it reappears on the screen. When the Navigator pushes a new route
  /// on the top of its stack, the old topmost route's secondaryAnimation
1164
  /// runs from 0.0 to 1.0. When the Navigator pops the topmost route, the
1165 1166
  /// secondaryAnimation for the route below it runs from 1.0 to 0.0.
  ///
1167
  /// {@tool snippet}
1168
  /// The example below adds a transition that's driven by the
1169
  /// [secondaryAnimation]. When this route disappears because a new route has
1170 1171 1172 1173 1174
  /// been pushed on top of it, it translates in the opposite direction of
  /// the new route. Likewise when the route is exposed because the topmost
  /// route has been popped off.
  ///
  /// ```dart
1175
  /// PageRouteBuilder<void>(
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
  ///   pageBuilder: (BuildContext context,
  ///       Animation<double> animation,
  ///       Animation<double> secondaryAnimation,
  ///   ) {
  ///     return Scaffold(
  ///       appBar: AppBar(title: const Text('Hello')),
  ///       body: const Center(
  ///         child: Text('Hello World'),
  ///       ),
  ///     );
  ///   },
1187 1188 1189 1190 1191 1192
  ///   transitionsBuilder: (
  ///       BuildContext context,
  ///       Animation<double> animation,
  ///       Animation<double> secondaryAnimation,
  ///       Widget child,
  ///   ) {
1193
  ///     return SlideTransition(
1194
  ///       position: Tween<Offset>(
1195 1196
  ///         begin: const Offset(0.0, 1.0),
  ///         end: Offset.zero,
1197
  ///       ).animate(animation),
1198
  ///       child: SlideTransition(
1199
  ///         position: Tween<Offset>(
1200 1201
  ///           begin: Offset.zero,
  ///           end: const Offset(0.0, 1.0),
1202 1203 1204
  ///         ).animate(secondaryAnimation),
  ///         child: child,
  ///       ),
1205 1206 1207
  ///      );
  ///   },
  /// )
1208
  /// ```
1209
  /// {@end-tool}
1210 1211
  ///
  /// In practice the `secondaryAnimation` is used pretty rarely.
1212
  ///
1213
  /// The arguments to this method are as follows:
1214
  ///
1215 1216 1217
  ///  * `context`: The context in which the route is being built.
  ///  * [animation]: When the [Navigator] pushes a route on the top of its stack,
  ///    the new route's primary [animation] runs from 0.0 to 1.0. When the [Navigator]
1218
  ///    pops the topmost route this animation runs from 1.0 to 0.0.
1219 1220
  ///  * [secondaryAnimation]: When the Navigator pushes a new route
  ///    on the top of its stack, the old topmost route's [secondaryAnimation]
1221
  ///    runs from 0.0 to 1.0. When the [Navigator] pops the topmost route, the
1222
  ///    [secondaryAnimation] for the route below it runs from 1.0 to 0.0.
1223
  ///  * `child`, the page contents, as returned by [buildPage].
1224 1225 1226 1227 1228
  ///
  /// See also:
  ///
  ///  * [buildPage], which is used to describe the actual contents of the page,
  ///    and whose result is passed to the `child` argument of this method.
1229
  Widget buildTransitions(
1230 1231 1232 1233
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
    Widget child,
1234
  ) {
1235 1236 1237
    return child;
  }

1238
  @override
1239 1240
  void install() {
    super.install();
1241 1242
    _animationProxy = ProxyAnimation(super.animation);
    _secondaryAnimationProxy = ProxyAnimation(super.secondaryAnimation);
1243 1244
  }

1245
  @override
1246
  TickerFuture didPush() {
1247
    if (_scopeKey.currentState != null && navigator!.widget.requestFocus) {
1248
      navigator!.focusNode.enclosingScope?.setFirstFocus(_scopeKey.currentState!.focusScopeNode);
1249
    }
1250
    return super.didPush();
1251 1252
  }

1253 1254
  @override
  void didAdd() {
1255
    if (_scopeKey.currentState != null && navigator!.widget.requestFocus) {
1256
      navigator!.focusNode.enclosingScope?.setFirstFocus(_scopeKey.currentState!.focusScopeNode);
1257 1258 1259 1260
    }
    super.didAdd();
  }

1261 1262
  // The API for subclasses to override - used by this class

1263
  /// {@template flutter.widgets.ModalRoute.barrierDismissible}
Hixie's avatar
Hixie committed
1264
  /// Whether you can dismiss this route by tapping the modal barrier.
1265 1266 1267 1268 1269 1270 1271 1272
  ///
  /// The modal barrier is the scrim that is rendered behind each route, which
  /// generally prevents the user from interacting with the route below the
  /// current route, and normally partially obscures such routes.
  ///
  /// For example, when a dialog is on the screen, the page below the dialog is
  /// usually darkened by the modal barrier.
  ///
1273 1274 1275 1276
  /// If [barrierDismissible] is true, then tapping this barrier, pressing
  /// the escape key on the keyboard, or calling route popping functions
  /// such as [Navigator.pop] will cause the current route to be popped
  /// with null as the value.
1277 1278 1279
  ///
  /// If [barrierDismissible] is false, then tapping the barrier has no effect.
  ///
1280 1281 1282 1283 1284 1285 1286 1287
  /// If this getter would ever start returning a different value,
  /// either [changedInternalState] or [changedExternalState] should
  /// be invoked so that the change can take effect.
  ///
  /// It is safe to use `navigator.context` to look up inherited
  /// widgets here, because the [Navigator] calls
  /// [changedExternalState] whenever its dependencies change, and
  /// [changedExternalState] causes the modal barrier to rebuild.
1288
  ///
1289 1290
  /// See also:
  ///
1291
  ///  * [Navigator.pop], which is used to dismiss the route.
1292 1293
  ///  * [barrierColor], which controls the color of the scrim for this route.
  ///  * [ModalBarrier], the widget that implements this feature.
1294
  /// {@endtemplate}
1295
  bool get barrierDismissible;
1296

1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
  /// Whether the semantics of the modal barrier are included in the
  /// semantics tree.
  ///
  /// The modal barrier is the scrim that is rendered behind each route, which
  /// generally prevents the user from interacting with the route below the
  /// current route, and normally partially obscures such routes.
  ///
  /// If [semanticsDismissible] is true, then modal barrier semantics are
  /// included in the semantics tree.
  ///
  /// If [semanticsDismissible] is false, then modal barrier semantics are
1308
  /// excluded from the semantics tree and tapping on the modal barrier
1309
  /// has no effect.
1310 1311 1312 1313 1314 1315 1316 1317 1318
  ///
  /// If this getter would ever start returning a different value,
  /// either [changedInternalState] or [changedExternalState] should
  /// be invoked so that the change can take effect.
  ///
  /// It is safe to use `navigator.context` to look up inherited
  /// widgets here, because the [Navigator] calls
  /// [changedExternalState] whenever its dependencies change, and
  /// [changedExternalState] causes the modal barrier to rebuild.
1319 1320
  bool get semanticsDismissible => true;

1321
  /// {@template flutter.widgets.ModalRoute.barrierColor}
Hixie's avatar
Hixie committed
1322 1323
  /// The color to use for the modal barrier. If this is null, the barrier will
  /// be transparent.
1324
  ///
1325 1326 1327 1328 1329 1330 1331
  /// The modal barrier is the scrim that is rendered behind each route, which
  /// generally prevents the user from interacting with the route below the
  /// current route, and normally partially obscures such routes.
  ///
  /// For example, when a dialog is on the screen, the page below the dialog is
  /// usually darkened by the modal barrier.
  ///
1332 1333
  /// The color is ignored, and the barrier made invisible, when
  /// [ModalRoute.offstage] is true.
1334 1335 1336
  ///
  /// While the route is animating into position, the color is animated from
  /// transparent to the specified color.
1337
  /// {@endtemplate}
1338
  ///
1339 1340 1341 1342 1343 1344 1345 1346
  /// If this getter would ever start returning a different color, one
  /// of the [changedInternalState] or [changedExternalState] methods
  /// should be invoked so that the change can take effect.
  ///
  /// It is safe to use `navigator.context` to look up inherited
  /// widgets here, because the [Navigator] calls
  /// [changedExternalState] whenever its dependencies change, and
  /// [changedExternalState] causes the modal barrier to rebuild.
1347
  ///
1348 1349
  /// {@tool snippet}
  ///
1350 1351
  /// For example, to make the barrier color use the theme's
  /// background color, one could say:
1352 1353
  ///
  /// ```dart
1354
  /// Color get barrierColor => Theme.of(navigator.context).colorScheme.background;
1355 1356 1357 1358
  /// ```
  ///
  /// {@end-tool}
  ///
1359 1360 1361 1362 1363
  /// See also:
  ///
  ///  * [barrierDismissible], which controls the behavior of the barrier when
  ///    tapped.
  ///  * [ModalBarrier], the widget that implements this feature.
1364
  Color? get barrierColor;
1365

1366
  /// {@template flutter.widgets.ModalRoute.barrierLabel}
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
  /// The semantic label used for a dismissible barrier.
  ///
  /// If the barrier is dismissible, this label will be read out if
  /// accessibility tools (like VoiceOver on iOS) focus on the barrier.
  ///
  /// The modal barrier is the scrim that is rendered behind each route, which
  /// generally prevents the user from interacting with the route below the
  /// current route, and normally partially obscures such routes.
  ///
  /// For example, when a dialog is on the screen, the page below the dialog is
  /// usually darkened by the modal barrier.
1378
  /// {@endtemplate}
1379
  ///
1380 1381 1382 1383 1384 1385 1386 1387
  /// If this getter would ever start returning a different label,
  /// either [changedInternalState] or [changedExternalState] should
  /// be invoked so that the change can take effect.
  ///
  /// It is safe to use `navigator.context` to look up inherited
  /// widgets here, because the [Navigator] calls
  /// [changedExternalState] whenever its dependencies change, and
  /// [changedExternalState] causes the modal barrier to rebuild.
1388
  ///
1389 1390 1391 1392 1393
  /// See also:
  ///
  ///  * [barrierDismissible], which controls the behavior of the barrier when
  ///    tapped.
  ///  * [ModalBarrier], the widget that implements this feature.
1394
  String? get barrierLabel;
1395

1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
  /// The curve that is used for animating the modal barrier in and out.
  ///
  /// The modal barrier is the scrim that is rendered behind each route, which
  /// generally prevents the user from interacting with the route below the
  /// current route, and normally partially obscures such routes.
  ///
  /// For example, when a dialog is on the screen, the page below the dialog is
  /// usually darkened by the modal barrier.
  ///
  /// While the route is animating into position, the color is animated from
  /// transparent to the specified [barrierColor].
  ///
1408 1409 1410 1411 1412 1413 1414 1415
  /// If this getter would ever start returning a different curve,
  /// either [changedInternalState] or [changedExternalState] should
  /// be invoked so that the change can take effect.
  ///
  /// It is safe to use `navigator.context` to look up inherited
  /// widgets here, because the [Navigator] calls
  /// [changedExternalState] whenever its dependencies change, and
  /// [changedExternalState] causes the modal barrier to rebuild.
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
  ///
  /// It defaults to [Curves.ease].
  ///
  /// See also:
  ///
  ///  * [barrierColor], which determines the color that the modal transitions
  ///    to.
  ///  * [Curves] for a collection of common curves.
  ///  * [AnimatedModalBarrier], the widget that implements this feature.
  Curve get barrierCurve => Curves.ease;

1427
  /// {@template flutter.widgets.ModalRoute.maintainState}
1428 1429 1430 1431 1432 1433 1434
  /// Whether the route should remain in memory when it is inactive.
  ///
  /// If this is true, then the route is maintained, so that any futures it is
  /// holding from the next route will properly resolve when the next route
  /// pops. If this is not necessary, this can be set to false to allow the
  /// framework to entirely discard the route's widget hierarchy when it is not
  /// visible.
1435 1436 1437 1438
  ///
  /// Setting [maintainState] to false does not guarantee that the route will be
  /// discarded. For instance, it will not be descarded if it is still visible
  /// because the next above it is not opaque (e.g. it is a popup dialog).
1439
  /// {@endtemplate}
1440
  ///
1441 1442 1443
  /// If this getter would ever start returning a different value, the
  /// [changedInternalState] should be invoked so that the change can take
  /// effect.
1444 1445 1446 1447 1448
  ///
  /// See also:
  ///
  ///  * [OverlayEntry.maintainState], which is the underlying implementation
  ///    of this property.
1449 1450
  bool get maintainState;

1451 1452 1453

  // The API for _ModalScope and HeroController

1454 1455 1456 1457 1458 1459 1460
  /// Whether this route is currently offstage.
  ///
  /// On the first frame of a route's entrance transition, the route is built
  /// [Offstage] using an animation progress of 1.0. The route is invisible and
  /// non-interactive, but each widget has its final size and position. This
  /// mechanism lets the [HeroController] determine the final local of any hero
  /// widgets being animated as part of the transition.
1461 1462 1463
  ///
  /// The modal barrier, if any, is not rendered if [offstage] is true (see
  /// [barrierColor]).
1464 1465
  ///
  /// Whenever this changes value, [changedInternalState] is called.
1466 1467
  bool get offstage => _offstage;
  bool _offstage = false;
1468
  set offstage(bool value) {
1469
    if (_offstage == value) {
1470
      return;
1471
    }
1472 1473 1474
    setState(() {
      _offstage = value;
    });
1475 1476
    _animationProxy!.parent = _offstage ? kAlwaysCompleteAnimation : super.animation;
    _secondaryAnimationProxy!.parent = _offstage ? kAlwaysDismissedAnimation : super.secondaryAnimation;
1477
    changedInternalState();
1478 1479
  }

1480
  /// The build context for the subtree containing the primary content of this route.
1481
  BuildContext? get subtreeContext => _subtreeKey.currentContext;
1482

1483
  @override
1484 1485
  Animation<double>? get animation => _animationProxy;
  ProxyAnimation? _animationProxy;
1486 1487

  @override
1488 1489
  Animation<double>? get secondaryAnimation => _secondaryAnimationProxy;
  ProxyAnimation? _secondaryAnimationProxy;
1490

1491 1492
  final List<WillPopCallback> _willPopCallbacks = <WillPopCallback>[];

1493 1494 1495 1496 1497
  /// Returns [RoutePopDisposition.doNotPop] if any of callbacks added with
  /// [addScopedWillPopCallback] returns either false or null. If they all
  /// return true, the base [Route.willPop]'s result will be returned. The
  /// callbacks will be called in the order they were added, and will only be
  /// called if all previous callbacks returned true.
1498 1499 1500 1501
  ///
  /// Typically this method is not overridden because applications usually
  /// don't create modal routes directly, they use higher level primitives
  /// like [showDialog]. The scoped [WillPopCallback] list makes it possible
1502
  /// for ModalRoute descendants to collectively define the value of [willPop].
1503 1504 1505
  ///
  /// See also:
  ///
1506 1507 1508 1509 1510
  ///  * [Form], which provides an `onWillPop` callback that uses this mechanism.
  ///  * [addScopedWillPopCallback], which adds a callback to the list this
  ///    method checks.
  ///  * [removeScopedWillPopCallback], which removes a callback from the list
  ///    this method checks.
1511
  @override
1512
  Future<RoutePopDisposition> willPop() async {
1513
    final _ModalScopeState<T>? scope = _scopeKey.currentState;
1514
    assert(scope != null);
1515
    for (final WillPopCallback callback in List<WillPopCallback>.of(_willPopCallbacks)) {
1516
      if (!await callback()) {
1517
        return RoutePopDisposition.doNotPop;
1518
      }
1519
    }
1520
    return super.willPop();
1521 1522 1523 1524
  }

  /// Enables this route to veto attempts by the user to dismiss it.
  ///
1525
  /// {@tool snippet}
1526 1527 1528 1529 1530 1531
  /// This callback is typically added using a [WillPopScope] widget. That
  /// widget finds the enclosing [ModalRoute] and uses this function to register
  /// this callback:
  ///
  /// ```dart
  /// Widget build(BuildContext context) {
1532
  ///   return WillPopScope(
1533 1534 1535 1536 1537
  ///     onWillPop: () async {
  ///       // ask the user if they are sure
  ///       return true;
  ///     },
  ///     child: Container(),
1538 1539 1540
  ///   );
  /// }
  /// ```
1541
  /// {@end-tool}
1542 1543
  ///
  /// This callback runs asynchronously and it's possible that it will be called
1544
  /// after its route has been disposed. The callback should check [State.mounted]
1545 1546 1547 1548 1549 1550
  /// before doing anything.
  ///
  /// A typical application of this callback would be to warn the user about
  /// unsaved [Form] data if the user attempts to back out of the form. In that
  /// case, use the [Form.onWillPop] property to register the callback.
  ///
1551
  /// {@tool snippet}
1552
  /// To register a callback manually, look up the enclosing [ModalRoute] in a
1553
  /// [State.didChangeDependencies] callback:
1554 1555
  ///
  /// ```dart
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
  /// abstract class _MyWidgetState extends State<MyWidget> {
  ///   ModalRoute<dynamic>? _route;
  ///
  ///   // ...
  ///
  ///   @override
  ///   void didChangeDependencies() {
  ///    super.didChangeDependencies();
  ///    _route?.removeScopedWillPopCallback(askTheUserIfTheyAreSure);
  ///    _route = ModalRoute.of(context);
  ///    _route?.addScopedWillPopCallback(askTheUserIfTheyAreSure);
  ///   }
1568 1569
  /// }
  /// ```
1570
  /// {@end-tool}
1571
  ///
1572
  /// {@tool snippet}
1573 1574 1575 1576
  /// If you register a callback manually, be sure to remove the callback with
  /// [removeScopedWillPopCallback] by the time the widget has been disposed. A
  /// stateful widget can do this in its dispose method (continuing the previous
  /// example):
1577 1578
  ///
  /// ```dart
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
  /// abstract class _MyWidgetState2 extends State<MyWidget> {
  ///   ModalRoute<dynamic>? _route;
  ///
  ///   // ...
  ///
  ///   @override
  ///   void dispose() {
  ///     _route?.removeScopedWillPopCallback(askTheUserIfTheyAreSure);
  ///     _route = null;
  ///     super.dispose();
  ///   }
1590 1591
  /// }
  /// ```
1592
  /// {@end-tool}
1593
  ///
1594 1595
  /// See also:
  ///
1596 1597 1598 1599 1600 1601
  ///  * [WillPopScope], which manages the registration and unregistration
  ///    process automatically.
  ///  * [Form], which provides an `onWillPop` callback that uses this mechanism.
  ///  * [willPop], which runs the callbacks added with this method.
  ///  * [removeScopedWillPopCallback], which removes a callback from the list
  ///    that [willPop] checks.
1602
  void addScopedWillPopCallback(WillPopCallback callback) {
1603 1604
    assert(_scopeKey.currentState != null, 'Tried to add a willPop callback to a route that is not currently in the tree.');
    _willPopCallbacks.add(callback);
1605 1606 1607 1608 1609 1610
  }

  /// Remove one of the callbacks run by [willPop].
  ///
  /// See also:
  ///
1611 1612 1613
  ///  * [Form], which provides an `onWillPop` callback that uses this mechanism.
  ///  * [addScopedWillPopCallback], which adds callback to the list
  ///    checked by [willPop].
1614
  void removeScopedWillPopCallback(WillPopCallback callback) {
1615 1616
    assert(_scopeKey.currentState != null, 'Tried to remove a willPop callback from a route that is not currently in the tree.');
    _willPopCallbacks.remove(callback);
1617 1618
  }

1619 1620
  /// True if one or more [WillPopCallback] callbacks exist.
  ///
1621 1622 1623 1624
  /// This method is used to disable the horizontal swipe pop gesture supported
  /// by [MaterialPageRoute] for [TargetPlatform.iOS] and
  /// [TargetPlatform.macOS]. If a pop might be vetoed, then the back gesture is
  /// disabled.
1625
  ///
1626 1627 1628 1629
  /// The [buildTransitions] method will not be called again if this changes,
  /// since it can change during the build as descendants of the route add or
  /// remove callbacks.
  ///
1630 1631
  /// See also:
  ///
1632 1633 1634 1635
  ///  * [addScopedWillPopCallback], which adds a callback.
  ///  * [removeScopedWillPopCallback], which removes a callback.
  ///  * [willHandlePopInternally], which reports on another reason why
  ///    a pop might be vetoed.
1636
  @protected
1637
  bool get hasScopedWillPopCallback {
1638 1639 1640 1641
    return _willPopCallbacks.isNotEmpty;
  }

  @override
1642
  void didChangePrevious(Route<dynamic>? previousRoute) {
1643 1644
    super.didChangePrevious(previousRoute);
    changedInternalState();
1645
  }
1646

1647 1648 1649 1650
  @override
  void changedInternalState() {
    super.changedInternalState();
    setState(() { /* internal state already changed */ });
1651
    _modalBarrier.markNeedsBuild();
1652
    _modalScope.maintainState = maintainState;
1653 1654 1655
  }

  @override
1656 1657
  void changedExternalState() {
    super.changedExternalState();
1658
    _modalBarrier.markNeedsBuild();
1659
    if (_scopeKey.currentState != null) {
1660
      _scopeKey.currentState!._forceRebuildPage();
1661
    }
1662 1663 1664 1665
  }

  /// Whether this route can be popped.
  ///
1666 1667 1668
  /// A route can be popped if there is at least one active route below it, or
  /// if [willHandlePopInternally] returns true.
  ///
1669 1670 1671
  /// When this changes, if the route is visible, the route will
  /// rebuild, and any widgets that used [ModalRoute.of] will be
  /// notified.
1672
  bool get canPop => hasActiveRouteBelow || willHandlePopInternally;
1673

1674 1675 1676 1677
  /// Whether an [AppBar] in the route should automatically add a back button or
  /// close button.
  ///
  /// This getter returns true if there is at least one active route below it,
1678
  /// or there is at least one [LocalHistoryEntry] with [impliesAppBarDismissal]
1679 1680 1681
  /// set to true
  bool get impliesAppBarDismissal => hasActiveRouteBelow || _entriesImpliesAppBarDismissal > 0;

1682 1683
  // Internals

1684 1685 1686
  final GlobalKey<_ModalScopeState<T>> _scopeKey = GlobalKey<_ModalScopeState<T>>();
  final GlobalKey _subtreeKey = GlobalKey();
  final PageStorageBucket _storageBucket = PageStorageBucket();
1687

1688
  // one of the builders
1689
  late OverlayEntry _modalBarrier;
1690
  Widget _buildModalBarrier(BuildContext context) {
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
    Widget barrier = buildModalBarrier();
    if (filter != null) {
      barrier = BackdropFilter(
        filter: filter!,
        child: barrier,
      );
    }
    barrier = IgnorePointer(
      ignoring: animation!.status == AnimationStatus.reverse || // changedInternalState is called when animation.status updates
                animation!.status == AnimationStatus.dismissed, // dismissed is possible when doing a manual pop gesture
      child: barrier,
    );
    if (semanticsDismissible && barrierDismissible) {
      // To be sorted after the _modalScope.
      barrier = Semantics(
        sortKey: const OrdinalSortKey(1.0),
        child: barrier,
      );
    }
    return barrier;
  }

  /// Build the barrier for this [ModalRoute], subclasses can override
  /// this method to create their own barrier with customized features such as
  /// color or accessibility focus size.
  ///
  /// See also:
  /// * [ModalBarrier], which is typically used to build a barrier.
  /// * [ModalBottomSheetRoute], which overrides this method to build a
  ///   customized barrier.
  Widget buildModalBarrier() {
1722
    Widget barrier;
1723
    if (barrierColor != null && barrierColor!.alpha != 0 && !offstage) { // changedInternalState is called if barrierColor or offstage updates
1724
      assert(barrierColor != barrierColor!.withOpacity(0.0));
1725
      final Animation<Color?> color = animation!.drive(
1726
        ColorTween(
1727
          begin: barrierColor!.withOpacity(0.0),
1728 1729
          end: barrierColor, // changedInternalState is called if barrierColor updates
        ).chain(CurveTween(curve: barrierCurve)), // changedInternalState is called if barrierCurve updates
1730
      );
1731
      barrier = AnimatedModalBarrier(
1732
        color: color,
1733 1734
        dismissible: barrierDismissible, // changedInternalState is called if barrierDismissible updates
        semanticsLabel: barrierLabel, // changedInternalState is called if barrierLabel updates
1735
        barrierSemanticsDismissible: semanticsDismissible,
Hixie's avatar
Hixie committed
1736 1737
      );
    } else {
1738
      barrier = ModalBarrier(
1739 1740
        dismissible: barrierDismissible, // changedInternalState is called if barrierDismissible updates
        semanticsLabel: barrierLabel, // changedInternalState is called if barrierLabel updates
1741
        barrierSemanticsDismissible: semanticsDismissible,
1742
      );
Hixie's avatar
Hixie committed
1743
    }
1744

1745
    return barrier;
1746 1747
  }

1748 1749
  // We cache the part of the modal scope that doesn't change from frame to
  // frame so that we minimize the amount of building that happens.
1750
  Widget? _modalScopeCache;
1751

1752
  // one of the builders
1753
  Widget _buildModalScope(BuildContext context) {
1754 1755 1756 1757 1758 1759 1760
    // To be sorted before the _modalBarrier.
    return _modalScopeCache ??= Semantics(
      sortKey: const OrdinalSortKey(0.0),
      child: _ModalScope<T>(
        key: _scopeKey,
        route: this,
        // _ModalScope calls buildTransitions() and buildChild(), defined above
1761
      ),
1762 1763 1764
    );
  }

1765
  late OverlayEntry _modalScope;
1766

1767
  @override
1768 1769 1770 1771 1772
  Iterable<OverlayEntry> createOverlayEntries() {
    return <OverlayEntry>[
      _modalBarrier = OverlayEntry(builder: _buildModalBarrier),
      _modalScope = OverlayEntry(builder: _buildModalScope, maintainState: maintainState),
    ];
1773
  }
1774

1775
  @override
1776
  String toString() => '${objectRuntimeType(this, 'ModalRoute')}($settings, animation: $_animation)';
1777
}
Hixie's avatar
Hixie committed
1778 1779

/// A modal route that overlays a widget over the current route.
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792
///
/// {@macro flutter.widgets.ModalRoute.barrierDismissible}
///
/// {@tool dartpad}
/// This example shows how to create a dialog box that is dismissible.
///
/// ** See code in examples/api/lib/widgets/routes/popup_route.0.dart **
/// {@end-tool}
///
/// See also:
///
///   * [ModalRoute], which is the base class for this class.
///   * [Navigator.pop], which is used to dismiss the route.
Hixie's avatar
Hixie committed
1793
abstract class PopupRoute<T> extends ModalRoute<T> {
1794 1795
  /// Initializes the [PopupRoute].
  PopupRoute({
1796 1797
    super.settings,
    super.filter,
1798
    super.traversalEdgeBehavior,
1799
  });
1800

1801
  @override
Hixie's avatar
Hixie committed
1802
  bool get opaque => false;
1803

1804 1805
  @override
  bool get maintainState => true;
1806 1807

  @override
1808
  bool get allowSnapshotting => false;
Hixie's avatar
Hixie committed
1809
}
1810 1811 1812 1813

/// A [Navigator] observer that notifies [RouteAware]s of changes to the
/// state of their [Route].
///
1814 1815 1816
/// [RouteObserver] informs subscribers whenever a route of type `R` is pushed
/// on top of their own route of type `R` or popped from it. This is for example
/// useful to keep track of page transitions, e.g. a `RouteObserver<PageRoute>`
1817 1818 1819
/// will inform subscribed [RouteAware]s whenever the user navigates away from
/// the current page route to another page route.
///
1820 1821 1822 1823 1824
/// To be informed about route changes of any type, consider instantiating a
/// `RouteObserver<Route>`.
///
/// ## Type arguments
///
1825 1826 1827
/// When using more aggressive [lints](https://dart.dev/lints),
/// in particular lints such as `always_specify_types`,
/// the Dart analyzer will require that certain types
1828 1829
/// be given with their type arguments. Since the [Route] class and its
/// subclasses have a type argument, this includes the arguments passed to this
1830
/// class. Consider using `dynamic` to specify the entire class of routes rather
1831
/// than only specific subtypes. For example, to watch for all [ModalRoute]
1832
/// variants, the `RouteObserver<ModalRoute<dynamic>>` type may be used.
1833
///
1834
/// {@tool snippet}
1835
///
1836
/// To make a [StatefulWidget] aware of its current [Route] state, implement
1837
/// [RouteAware] in its [State] and subscribe it to a [RouteObserver]:
1838 1839
///
/// ```dart
1840
/// // Register the RouteObserver as a navigation observer.
1841
/// final RouteObserver<ModalRoute<void>> routeObserver = RouteObserver<ModalRoute<void>>();
1842
///
1843
/// void main() {
1844 1845
///   runApp(MaterialApp(
///     home: Container(),
1846
///     navigatorObservers: <RouteObserver<ModalRoute<void>>>[ routeObserver ],
1847 1848 1849 1850
///   ));
/// }
///
/// class RouteAwareWidget extends StatefulWidget {
1851
///   const RouteAwareWidget({super.key});
1852 1853
///
///   @override
1854
///   State<RouteAwareWidget> createState() => RouteAwareWidgetState();
1855 1856 1857
/// }
///
/// // Implement RouteAware in a widget's state and subscribe it to the RouteObserver.
1858
/// class RouteAwareWidgetState extends State<RouteAwareWidget> with RouteAware {
1859
///
1860 1861 1862
///   @override
///   void didChangeDependencies() {
///     super.didChangeDependencies();
1863
///     routeObserver.subscribe(this, ModalRoute.of(context)!);
1864 1865 1866 1867 1868 1869 1870 1871 1872 1873
///   }
///
///   @override
///   void dispose() {
///     routeObserver.unsubscribe(this);
///     super.dispose();
///   }
///
///   @override
///   void didPush() {
1874
///     // Route was pushed onto navigator and is now topmost route.
1875 1876 1877 1878
///   }
///
///   @override
///   void didPopNext() {
1879
///     // Covering route was popped off the navigator.
1880 1881
///   }
///
1882
///   @override
1883
///   Widget build(BuildContext context) => Container();
1884
///
1885 1886
/// }
/// ```
1887
/// {@end-tool}
1888
class RouteObserver<R extends Route<dynamic>> extends NavigatorObserver {
1889
  final Map<R, Set<RouteAware>> _listeners = <R, Set<RouteAware>>{};
1890

1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903
  /// Whether this observer is managing changes for the specified route.
  ///
  /// If asserts are disabled, this method will throw an exception.
  @visibleForTesting
  bool debugObservingRoute(R route) {
    late bool contained;
    assert(() {
      contained = _listeners.containsKey(route);
      return true;
    }());
    return contained;
  }

1904 1905 1906 1907 1908
  /// Subscribe [routeAware] to be informed about changes to [route].
  ///
  /// Going forward, [routeAware] will be informed about qualifying changes
  /// to [route], e.g. when [route] is covered by another route or when [route]
  /// is popped off the [Navigator] stack.
1909
  void subscribe(RouteAware routeAware, R route) {
1910
    final Set<RouteAware> subscribers = _listeners.putIfAbsent(route, () => <RouteAware>{});
1911
    if (subscribers.add(routeAware)) {
1912 1913 1914 1915
      routeAware.didPush();
    }
  }

1916 1917
  /// Unsubscribe [routeAware].
  ///
1918 1919
  /// [routeAware] is no longer informed about changes to its route. If the given argument was
  /// subscribed to multiple types, this will unregister it (once) from each type.
1920
  void unsubscribe(RouteAware routeAware) {
1921 1922
    final List<R> routes = _listeners.keys.toList();
    for (final R route in routes) {
1923
      final Set<RouteAware>? subscribers = _listeners[route];
1924 1925 1926 1927 1928 1929
      if (subscribers != null) {
        subscribers.remove(routeAware);
        if (subscribers.isEmpty) {
          _listeners.remove(route);
        }
      }
1930
    }
1931 1932 1933
  }

  @override
1934
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
1935
    if (route is R && previousRoute is R) {
1936
      final List<RouteAware>? previousSubscribers = _listeners[previousRoute]?.toList();
1937 1938

      if (previousSubscribers != null) {
1939
        for (final RouteAware routeAware in previousSubscribers) {
1940 1941 1942 1943
          routeAware.didPopNext();
        }
      }

1944
      final List<RouteAware>? subscribers = _listeners[route]?.toList();
1945 1946

      if (subscribers != null) {
1947
        for (final RouteAware routeAware in subscribers) {
1948 1949 1950
          routeAware.didPop();
        }
      }
1951 1952 1953 1954
    }
  }

  @override
1955
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
1956
    if (route is R && previousRoute is R) {
1957
      final Set<RouteAware>? previousSubscribers = _listeners[previousRoute];
1958 1959

      if (previousSubscribers != null) {
1960
        for (final RouteAware routeAware in previousSubscribers) {
1961 1962 1963
          routeAware.didPushNext();
        }
      }
1964 1965 1966 1967
    }
  }
}

1968 1969 1970 1971
/// An interface for objects that are aware of their current [Route].
///
/// This is used with [RouteObserver] to make a widget aware of changes to the
/// [Navigator]'s session history.
1972
abstract mixin class RouteAware {
1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
  /// Called when the top route has been popped off, and the current route
  /// shows up.
  void didPopNext() { }

  /// Called when the current route has been pushed.
  void didPush() { }

  /// Called when the current route has been popped off.
  void didPop() { }

  /// Called when a new route has been pushed, and the current route is no
  /// longer visible.
  void didPushNext() { }
1986
}
1987

1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009
/// A general dialog route which allows for customization of the dialog popup.
///
/// It is used internally by [showGeneralDialog] or can be directly pushed
/// onto the [Navigator] stack to enable state restoration. See
/// [showGeneralDialog] for a state restoration app example.
///
/// This function takes a `pageBuilder`, which typically builds a dialog.
/// 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 `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`, the default
/// color `Colors.black54` is used.
///
/// The `settings` argument define the settings for this route. See
/// [RouteSettings] for details.
///
2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024
/// {@template flutter.widgets.RawDialogRoute}
/// A [DisplayFeature] can split the screen into sub-screens. The closest one to
/// [anchorPoint] is used to render the content.
///
/// If no [anchorPoint] is provided, then [Directionality] is used:
///
///   * for [TextDirection.ltr], [anchorPoint] is `Offset.zero`, which will
///     cause the content to appear in the top-left sub-screen.
///   * for [TextDirection.rtl], [anchorPoint] is `Offset(double.maxFinite, 0)`,
///     which will cause the content to appear in the top-right sub-screen.
///
/// If no [anchorPoint] is provided, and there is no [Directionality] ancestor
/// widget in the tree, then the widget asserts during build in debug mode.
/// {@endtemplate}
///
2025 2026
/// See also:
///
2027 2028
///  * [DisplayFeatureSubScreen], which documents the specifics of how
///    [DisplayFeature]s can split the screen into sub-screens.
2029 2030 2031 2032 2033 2034
///  * [showGeneralDialog], which is a way to display a RawDialogRoute.
///  * [showDialog], which is a way to display a DialogRoute.
///  * [showCupertinoDialog], which displays an iOS-style dialog.
class RawDialogRoute<T> extends PopupRoute<T> {
  /// A general dialog route which allows for customization of the dialog popup.
  RawDialogRoute({
2035
    required RoutePageBuilder pageBuilder,
2036
    bool barrierDismissible = true,
2037
    Color? barrierColor = const Color(0x80000000),
2038
    String? barrierLabel,
2039
    Duration transitionDuration = const Duration(milliseconds: 200),
2040
    RouteTransitionsBuilder? transitionBuilder,
2041
    super.settings,
2042
    this.anchorPoint,
2043
    super.traversalEdgeBehavior,
2044
  }) : _pageBuilder = pageBuilder,
2045 2046 2047 2048
       _barrierDismissible = barrierDismissible,
       _barrierLabel = barrierLabel,
       _barrierColor = barrierColor,
       _transitionDuration = transitionDuration,
2049
       _transitionBuilder = transitionBuilder;
2050 2051 2052 2053 2054 2055 2056 2057

  final RoutePageBuilder _pageBuilder;

  @override
  bool get barrierDismissible => _barrierDismissible;
  final bool _barrierDismissible;

  @override
2058 2059
  String? get barrierLabel => _barrierLabel;
  final String? _barrierLabel;
2060 2061

  @override
2062 2063
  Color? get barrierColor => _barrierColor;
  final Color? _barrierColor;
2064 2065 2066 2067 2068

  @override
  Duration get transitionDuration => _transitionDuration;
  final Duration _transitionDuration;

2069
  final RouteTransitionsBuilder? _transitionBuilder;
2070

2071 2072 2073
  /// {@macro flutter.widgets.DisplayFeatureSubScreen.anchorPoint}
  final Offset? anchorPoint;

2074 2075
  @override
  Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
2076
    return Semantics(
2077 2078
      scopesRoute: true,
      explicitChildNodes: true,
2079 2080 2081 2082
      child: DisplayFeatureSubScreen(
        anchorPoint: anchorPoint,
        child: _pageBuilder(context, animation, secondaryAnimation),
      ),
2083 2084 2085 2086 2087 2088
    );
  }

  @override
  Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
    if (_transitionBuilder == null) {
2089
      // Some default transition.
2090
      return FadeTransition(
2091 2092 2093 2094 2095 2096
        opacity: CurvedAnimation(
          parent: animation,
          curve: Curves.linear,
        ),
        child: child,
      );
2097
    }
2098
    return _transitionBuilder!(context, animation, secondaryAnimation, child);
2099 2100 2101 2102 2103 2104 2105 2106 2107 2108
  }
}

/// Displays a dialog above the current contents of the app.
///
/// This function allows for customization of aspects of the dialog popup.
///
/// This function takes a `pageBuilder` which is used to build the primary
/// content of the route (typically a dialog widget). Content below the dialog
/// is dimmed with a [ModalBarrier]. The widget returned by the `pageBuilder`
2109
/// does not share a context with the location that [showGeneralDialog] is
2110 2111 2112 2113
/// originally called from. Use a [StatefulBuilder] or a custom
/// [StatefulWidget] if the dialog needs to update dynamically. The
/// `pageBuilder` argument can not be null.
///
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
/// 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.
///
/// 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.
///
/// 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)`.
2126 2127 2128
///
/// The `barrierDismissible` argument is used to determine whether this route
/// can be dismissed by tapping the modal barrier. This argument defaults
2129
/// to false. If `barrierDismissible` is true, a non-null `barrierLabel` must be
2130 2131 2132
/// provided.
///
/// The `barrierLabel` argument is the semantic label used for a dismissible
2133
/// barrier. This argument defaults to `null`.
2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145
///
/// The `barrierColor` argument is the color used for the modal barrier. This
/// argument defaults to `Color(0x80000000)`.
///
/// The `transitionDuration` argument is used to determine how long it takes
/// for the route to arrive on or leave off the screen. This argument defaults
/// to 200 milliseconds.
///
/// The `transitionBuilder` argument is used to define how the route arrives on
/// and leaves off the screen. By default, the transition is a linear fade of
/// the page's contents.
///
2146 2147 2148
/// The `routeSettings` will be used in the construction of the dialog's route.
/// See [RouteSettings] for more details.
///
2149 2150
/// {@macro flutter.widgets.RawDialogRoute}
///
2151 2152 2153
/// Returns a [Future] that resolves to the value (if any) that was passed to
/// [Navigator.pop] when the dialog was closed.
///
2154 2155 2156 2157 2158 2159 2160 2161
/// ### 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 [RawDialogRoute].
///
/// For more information about state restoration, see [RestorationManager].
///
2162
/// {@tool sample}
2163 2164 2165 2166 2167 2168 2169
/// This sample demonstrates how to create a restorable dialog. This is
/// accomplished by enabling state restoration by specifying
/// [WidgetsApp.restorationScopeId] and using [Navigator.restorablePush] to
/// push [RawDialogRoute] when the button is tapped.
///
/// {@macro flutter.widgets.RestorationManager}
///
2170
/// ** See code in examples/api/lib/widgets/routes/show_general_dialog.0.dart **
2171 2172
/// {@end-tool}
///
2173
/// See also:
2174
///
2175 2176
///  * [DisplayFeatureSubScreen], which documents the specifics of how
///    [DisplayFeature]s can split the screen into sub-screens.
2177 2178
///  * [showDialog], which displays a Material-style dialog.
///  * [showCupertinoDialog], which displays an iOS-style dialog.
2179
Future<T?> showGeneralDialog<T extends Object?>({
2180 2181
  required BuildContext context,
  required RoutePageBuilder pageBuilder,
2182
  bool barrierDismissible = false,
2183
  String? barrierLabel,
2184 2185
  Color barrierColor = const Color(0x80000000),
  Duration transitionDuration = const Duration(milliseconds: 200),
2186
  RouteTransitionsBuilder? transitionBuilder,
2187
  bool useRootNavigator = true,
2188
  RouteSettings? routeSettings,
2189
  Offset? anchorPoint,
2190 2191
}) {
  assert(!barrierDismissible || barrierLabel != null);
2192
  return Navigator.of(context, rootNavigator: useRootNavigator).push<T>(RawDialogRoute<T>(
2193 2194 2195 2196 2197 2198
    pageBuilder: pageBuilder,
    barrierDismissible: barrierDismissible,
    barrierLabel: barrierLabel,
    barrierColor: barrierColor,
    transitionDuration: transitionDuration,
    transitionBuilder: transitionBuilder,
2199
    settings: routeSettings,
2200
    anchorPoint: anchorPoint,
2201 2202 2203 2204 2205 2206 2207
  ));
}

/// Signature for the function that builds a route's primary contents.
/// Used in [PageRouteBuilder] and [showGeneralDialog].
///
/// See [ModalRoute.buildPage] for complete definition of the parameters.
2208
typedef RoutePageBuilder = Widget Function(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation);
2209 2210 2211 2212 2213

/// Signature for the function that builds a route's transitions.
/// Used in [PageRouteBuilder] and [showGeneralDialog].
///
/// See [ModalRoute.buildTransitions] for complete definition of the parameters.
2214
typedef RouteTransitionsBuilder = Widget Function(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child);