routes.dart 86 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 721 722 723
  @Deprecated(
    'Use popDisposition instead. '
    'This feature was deprecated after v3.12.0-1.0.pre.',
  )
724
  @override
725
  Future<RoutePopDisposition> willPop() async {
726
    if (willHandlePopInternally) {
727
      return RoutePopDisposition.pop;
728
    }
729
    return super.willPop();
730 731
  }

732 733 734 735 736 737 738 739
  @override
  RoutePopDisposition get popDisposition {
    if (willHandlePopInternally) {
      return RoutePopDisposition.pop;
    }
    return super.popDisposition;
  }

740
  @override
741
  bool didPop(T? result) {
742 743
    if (_localHistory != null && _localHistory!.isNotEmpty) {
      final LocalHistoryEntry entry = _localHistory!.removeLast();
Hixie's avatar
Hixie committed
744 745 746
      assert(entry._owner == this);
      entry._owner = null;
      entry._notifyRemoved();
747 748 749 750 751
      bool internalStateChanged = false;
      if (entry.impliesAppBarDismissal) {
        _entriesImpliesAppBarDismissal -= 1;
        internalStateChanged = _entriesImpliesAppBarDismissal == 0;
      }
752
      if (_localHistory!.isEmpty || internalStateChanged) {
753
        changedInternalState();
754
      }
Hixie's avatar
Hixie committed
755 756 757 758
      return false;
    }
    return super.didPop(result);
  }
759 760

  @override
Hixie's avatar
Hixie committed
761
  bool get willHandlePopInternally {
762
    return _localHistory != null && _localHistory!.isNotEmpty;
Hixie's avatar
Hixie committed
763
  }
Hixie's avatar
Hixie committed
764 765
}

766
class _DismissModalAction extends DismissAction {
767 768 769 770 771 772
  _DismissModalAction(this.context);

  final BuildContext context;

  @override
  bool isEnabled(DismissIntent intent) {
773
    final ModalRoute<dynamic> route = ModalRoute.of<dynamic>(context)!;
774 775 776
    return route.barrierDismissible;
  }

777 778
  @override
  Object invoke(DismissIntent intent) {
779
    return Navigator.of(context).maybePop();
780 781 782
  }
}

Hixie's avatar
Hixie committed
783
class _ModalScopeStatus extends InheritedWidget {
784
  const _ModalScopeStatus({
785 786
    required this.isCurrent,
    required this.canPop,
787
    required this.impliesAppBarDismissal,
788
    required this.route,
789
    required super.child,
790
  });
Hixie's avatar
Hixie committed
791

792
  final bool isCurrent;
793
  final bool canPop;
794
  final bool impliesAppBarDismissal;
795
  final Route<dynamic> route;
Hixie's avatar
Hixie committed
796

797
  @override
Hixie's avatar
Hixie committed
798
  bool updateShouldNotify(_ModalScopeStatus old) {
799
    return isCurrent != old.isCurrent ||
800
           canPop != old.canPop ||
801
           impliesAppBarDismissal != old.impliesAppBarDismissal ||
Hixie's avatar
Hixie committed
802 803 804
           route != old.route;
  }

805
  @override
806
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
807
    super.debugFillProperties(description);
808 809
    description.add(FlagProperty('isCurrent', value: isCurrent, ifTrue: 'active', ifFalse: 'inactive'));
    description.add(FlagProperty('canPop', value: canPop, ifTrue: 'can pop'));
810
    description.add(FlagProperty('impliesAppBarDismissal', value: impliesAppBarDismissal, ifTrue: 'implies app bar dismissal'));
Hixie's avatar
Hixie committed
811 812 813
  }
}

814
class _ModalScope<T> extends StatefulWidget {
815
  const _ModalScope({
816
    super.key,
817
    required this.route,
818
  });
819

820
  final ModalRoute<T> route;
821

822
  @override
823
  _ModalScopeState<T> createState() => _ModalScopeState<T>();
824 825
}

826 827 828 829 830
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.
831
  Widget? _page;
832 833

  // This is the combination of the two animations for the route.
834
  late Listenable _listenable;
835

836
  /// The node this scope will use for its root [FocusScope] widget.
837
  final FocusScopeNode focusScopeNode = FocusScopeNode(debugLabel: '$_ModalScopeState Focus Scope');
838
  final ScrollController primaryScrollController = ScrollController();
839

840
  @override
841 842
  void initState() {
    super.initState();
843
    final List<Listenable> animations = <Listenable>[
844 845
      if (widget.route.animation != null) widget.route.animation!,
      if (widget.route.secondaryAnimation != null) widget.route.secondaryAnimation!,
846
    ];
847
    _listenable = Listenable.merge(animations);
848 849
  }

850
  @override
851
  void didUpdateWidget(_ModalScope<T> oldWidget) {
852
    super.didUpdateWidget(oldWidget);
853
    assert(widget.route == oldWidget.route);
854
    _updateFocusScopeNode();
855 856
  }

857
  @override
858 859 860
  void didChangeDependencies() {
    super.didChangeDependencies();
    _page = null;
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
    _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);
    }
876 877
  }

878
  void _forceRebuildPage() {
879
    setState(() {
880
      _page = null;
881 882 883
    });
  }

884 885 886
  @override
  void dispose() {
    focusScopeNode.dispose();
887
    primaryScrollController.dispose();
888 889 890
    super.dispose();
  }

891 892 893 894 895
  bool get _shouldIgnoreFocusRequest {
    return widget.route.animation?.status == AnimationStatus.reverse ||
      (widget.route.navigator?.userGestureInProgress ?? false);
  }

896 897 898 899
  bool get _shouldRequestFocus {
    return widget.route.navigator!.widget.requestFocus;
  }

900 901
  // This should be called to wrap any changes to route.isCurrent, route.canPop,
  // and route.offstage.
902
  void _routeSetState(VoidCallback fn) {
903
    if (widget.route.isCurrent && !_shouldIgnoreFocusRequest && _shouldRequestFocus) {
904
      widget.route.navigator!.focusNode.enclosingScope?.setFirstFocus(focusScopeNode);
905
    }
906
    setState(fn);
907 908
  }

909
  @override
910
  Widget build(BuildContext context) {
911 912 913 914 915 916 917 918 919 920 921 922 923
    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
924
        impliesAppBarDismissal: widget.route.impliesAppBarDismissal,
925 926 927 928
        child: Offstage(
          offstage: widget.route.offstage, // _routeSetState is called if this updates
          child: PageStorage(
            bucket: widget.route._storageBucket, // immutable
929 930 931 932 933 934
            child: Builder(
              builder: (BuildContext context) {
                return Actions(
                  actions: <Type, Action<Intent>>{
                    DismissIntent: _DismissModalAction(context),
                  },
935 936 937 938
                  child: PrimaryScrollController(
                    controller: primaryScrollController,
                    child: FocusScope(
                      node: focusScopeNode, // immutable
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
                      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,
959 960
                                  );
                                },
961
                                child: child,
962
                              ),
963 964 965 966 967 968 969 970 971 972 973 974
                            );
                          },
                          child: _page ??= RepaintBoundary(
                            key: widget.route._subtreeKey, // immutable
                            child: Builder(
                              builder: (BuildContext context) {
                                return widget.route.buildPage(
                                  context,
                                  widget.route.animation!,
                                  widget.route.secondaryAnimation!,
                                );
                              },
975 976 977
                            ),
                          ),
                        ),
978
                      ),
979
                    ),
980
                  ),
981 982
                );
              },
983 984 985 986
            ),
          ),
        ),
      ),
987
    );
988 989 990
  }
}

991
/// A route that blocks interaction with previous routes.
992
///
993 994 995 996 997 998
/// [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.
999 1000 1001 1002
///
/// See also:
///
///  * [Route], which further documents the meaning of the `T` generic type argument.
1003
abstract class ModalRoute<T> extends TransitionRoute<T> with LocalHistoryRoute<T> {
1004
  /// Creates a route that blocks interaction with previous routes.
1005
  ModalRoute({
1006
    super.settings,
1007
    this.filter,
1008
    this.traversalEdgeBehavior,
1009
  });
1010 1011 1012 1013 1014

  /// 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.
1015
  final ui.ImageFilter? filter;
1016

1017 1018 1019 1020 1021 1022
  /// 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
1023 1024
  // The API for general users of this class

1025 1026
  /// Returns the modal route most closely associated with the given context.
  ///
1027
  /// Returns null if the given context is not associated with a modal route.
1028
  ///
1029 1030
  /// {@tool snippet}
  ///
1031 1032 1033
  /// Typical usage is as follows:
  ///
  /// ```dart
1034
  /// ModalRoute<int>? route = ModalRoute.of<int>(context);
1035
  /// ```
1036
  /// {@end-tool}
1037 1038
  ///
  /// The given [BuildContext] will be rebuilt if the state of the route changes
1039
  /// while it is visible (specifically, if [isCurrent] or [canPop] change value).
1040
  @optionalTypeArgs
1041
  static ModalRoute<T>? of<T extends Object?>(BuildContext context) {
1042 1043
    final _ModalScopeStatus? widget = context.dependOnInheritedWidgetOfExactType<_ModalScopeStatus>();
    return widget?.route as ModalRoute<T>?;
Hixie's avatar
Hixie committed
1044 1045
  }

1046 1047
  /// Schedule a call to [buildTransitions].
  ///
1048
  /// Whenever you need to change internal state for a [ModalRoute] object, make
1049
  /// the change in a function that you pass to [setState], as in:
1050 1051
  ///
  /// ```dart
1052
  /// setState(() { _myState = newValue; });
1053 1054
  /// ```
  ///
1055
  /// If you just change the state directly without calling [setState], then the
1056 1057 1058 1059 1060
  /// route will not be scheduled for rebuilding, meaning that its rendering
  /// will not be updated.
  @protected
  void setState(VoidCallback fn) {
    if (_scopeKey.currentState != null) {
1061
      _scopeKey.currentState!._routeSetState(fn);
1062 1063 1064 1065 1066 1067 1068 1069
    } 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
1070 1071 1072 1073 1074 1075
  /// 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) {
1076
    return (Route<dynamic> route) {
Hans Muller's avatar
Hans Muller committed
1077
      return !route.willHandlePopInternally
1078 1079
          && route is ModalRoute
          && route.settings.name == name;
Hans Muller's avatar
Hans Muller committed
1080 1081
    };
  }
1082 1083 1084

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

1085
  /// Override this method to build the primary content of this route.
1086
  ///
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
  /// 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.
  ///
1097 1098 1099 1100 1101 1102 1103 1104
  /// 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.
1105 1106 1107 1108 1109
  ///
  /// 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.
1110
  Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation);
1111

1112 1113
  /// Override this method to wrap the [child] with one or more transition
  /// widgets that define how the route arrives on and leaves the screen.
1114
  ///
1115 1116 1117 1118
  /// 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
1119 1120
  /// time the [Route]'s state changes while it is visible (e.g. if the value of
  /// [canPop] changes on the active route).
1121
  ///
1122
  /// The [buildTransitions] method is typically used to define transitions
1123 1124 1125 1126 1127 1128
  /// 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.
  ///
1129
  /// {@tool snippet}
1130 1131 1132 1133 1134 1135
  /// 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.
  ///
1136 1137 1138 1139
  /// 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.
  ///
1140
  /// ```dart
1141
  /// PageRouteBuilder<void>(
1142 1143 1144 1145
  ///   pageBuilder: (BuildContext context,
  ///       Animation<double> animation,
  ///       Animation<double> secondaryAnimation,
  ///   ) {
1146
  ///     return Scaffold(
1147 1148
  ///       appBar: AppBar(title: const Text('Hello')),
  ///       body: const Center(
1149
  ///         child: Text('Hello World'),
1150 1151 1152 1153 1154 1155 1156 1157 1158
  ///       ),
  ///     );
  ///   },
  ///   transitionsBuilder: (
  ///       BuildContext context,
  ///       Animation<double> animation,
  ///       Animation<double> secondaryAnimation,
  ///       Widget child,
  ///    ) {
1159 1160
  ///     return SlideTransition(
  ///       position: Tween<Offset>(
1161 1162
  ///         begin: const Offset(0.0, 1.0),
  ///         end: Offset.zero,
1163 1164 1165 1166
  ///       ).animate(animation),
  ///       child: child, // child is the value returned by pageBuilder
  ///     );
  ///   },
1167
  /// )
1168
  /// ```
1169
  /// {@end-tool}
1170
  ///
1171
  /// When the [Navigator] pushes a route on the top of its stack, the
1172 1173 1174 1175 1176
  /// [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
1177
  /// runs from 0.0 to 1.0. When the Navigator pops the topmost route, the
1178 1179
  /// secondaryAnimation for the route below it runs from 1.0 to 0.0.
  ///
1180
  /// {@tool snippet}
1181
  /// The example below adds a transition that's driven by the
1182
  /// [secondaryAnimation]. When this route disappears because a new route has
1183 1184 1185 1186 1187
  /// 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
1188
  /// PageRouteBuilder<void>(
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
  ///   pageBuilder: (BuildContext context,
  ///       Animation<double> animation,
  ///       Animation<double> secondaryAnimation,
  ///   ) {
  ///     return Scaffold(
  ///       appBar: AppBar(title: const Text('Hello')),
  ///       body: const Center(
  ///         child: Text('Hello World'),
  ///       ),
  ///     );
  ///   },
1200 1201 1202 1203 1204 1205
  ///   transitionsBuilder: (
  ///       BuildContext context,
  ///       Animation<double> animation,
  ///       Animation<double> secondaryAnimation,
  ///       Widget child,
  ///   ) {
1206
  ///     return SlideTransition(
1207
  ///       position: Tween<Offset>(
1208 1209
  ///         begin: const Offset(0.0, 1.0),
  ///         end: Offset.zero,
1210
  ///       ).animate(animation),
1211
  ///       child: SlideTransition(
1212
  ///         position: Tween<Offset>(
1213 1214
  ///           begin: Offset.zero,
  ///           end: const Offset(0.0, 1.0),
1215 1216 1217
  ///         ).animate(secondaryAnimation),
  ///         child: child,
  ///       ),
1218 1219 1220
  ///      );
  ///   },
  /// )
1221
  /// ```
1222
  /// {@end-tool}
1223 1224
  ///
  /// In practice the `secondaryAnimation` is used pretty rarely.
1225
  ///
1226
  /// The arguments to this method are as follows:
1227
  ///
1228 1229 1230
  ///  * `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]
1231
  ///    pops the topmost route this animation runs from 1.0 to 0.0.
1232 1233
  ///  * [secondaryAnimation]: When the Navigator pushes a new route
  ///    on the top of its stack, the old topmost route's [secondaryAnimation]
1234
  ///    runs from 0.0 to 1.0. When the [Navigator] pops the topmost route, the
1235
  ///    [secondaryAnimation] for the route below it runs from 1.0 to 0.0.
1236
  ///  * `child`, the page contents, as returned by [buildPage].
1237 1238 1239 1240 1241
  ///
  /// 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.
1242
  Widget buildTransitions(
1243 1244 1245 1246
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
    Widget child,
1247
  ) {
1248 1249 1250
    return child;
  }

1251
  @override
1252 1253
  void install() {
    super.install();
1254 1255
    _animationProxy = ProxyAnimation(super.animation);
    _secondaryAnimationProxy = ProxyAnimation(super.secondaryAnimation);
1256 1257
  }

1258
  @override
1259
  TickerFuture didPush() {
1260
    if (_scopeKey.currentState != null && navigator!.widget.requestFocus) {
1261
      navigator!.focusNode.enclosingScope?.setFirstFocus(_scopeKey.currentState!.focusScopeNode);
1262
    }
1263
    return super.didPush();
1264 1265
  }

1266 1267
  @override
  void didAdd() {
1268
    if (_scopeKey.currentState != null && navigator!.widget.requestFocus) {
1269
      navigator!.focusNode.enclosingScope?.setFirstFocus(_scopeKey.currentState!.focusScopeNode);
1270 1271 1272 1273
    }
    super.didAdd();
  }

1274 1275
  // The API for subclasses to override - used by this class

1276
  /// {@template flutter.widgets.ModalRoute.barrierDismissible}
Hixie's avatar
Hixie committed
1277
  /// Whether you can dismiss this route by tapping the modal barrier.
1278 1279 1280 1281 1282 1283 1284 1285
  ///
  /// 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.
  ///
1286 1287 1288 1289
  /// 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.
1290 1291 1292
  ///
  /// If [barrierDismissible] is false, then tapping the barrier has no effect.
  ///
1293 1294 1295 1296 1297 1298 1299 1300
  /// 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.
1301
  ///
1302 1303
  /// See also:
  ///
1304
  ///  * [Navigator.pop], which is used to dismiss the route.
1305 1306
  ///  * [barrierColor], which controls the color of the scrim for this route.
  ///  * [ModalBarrier], the widget that implements this feature.
1307
  /// {@endtemplate}
1308
  bool get barrierDismissible;
1309

1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
  /// 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
1321
  /// excluded from the semantics tree and tapping on the modal barrier
1322
  /// has no effect.
1323 1324 1325 1326 1327 1328 1329 1330 1331
  ///
  /// 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.
1332 1333
  bool get semanticsDismissible => true;

1334
  /// {@template flutter.widgets.ModalRoute.barrierColor}
Hixie's avatar
Hixie committed
1335 1336
  /// The color to use for the modal barrier. If this is null, the barrier will
  /// be transparent.
1337
  ///
1338 1339 1340 1341 1342 1343 1344
  /// 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.
  ///
1345 1346
  /// The color is ignored, and the barrier made invisible, when
  /// [ModalRoute.offstage] is true.
1347 1348 1349
  ///
  /// While the route is animating into position, the color is animated from
  /// transparent to the specified color.
1350
  /// {@endtemplate}
1351
  ///
1352 1353 1354 1355 1356 1357 1358 1359
  /// 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.
1360
  ///
1361 1362
  /// {@tool snippet}
  ///
1363 1364
  /// For example, to make the barrier color use the theme's
  /// background color, one could say:
1365 1366
  ///
  /// ```dart
1367
  /// Color get barrierColor => Theme.of(navigator.context).colorScheme.background;
1368 1369 1370 1371
  /// ```
  ///
  /// {@end-tool}
  ///
1372 1373 1374 1375 1376
  /// See also:
  ///
  ///  * [barrierDismissible], which controls the behavior of the barrier when
  ///    tapped.
  ///  * [ModalBarrier], the widget that implements this feature.
1377
  Color? get barrierColor;
1378

1379
  /// {@template flutter.widgets.ModalRoute.barrierLabel}
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
  /// 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.
1391
  /// {@endtemplate}
1392
  ///
1393 1394 1395 1396 1397 1398 1399 1400
  /// 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.
1401
  ///
1402 1403 1404 1405 1406
  /// See also:
  ///
  ///  * [barrierDismissible], which controls the behavior of the barrier when
  ///    tapped.
  ///  * [ModalBarrier], the widget that implements this feature.
1407
  String? get barrierLabel;
1408

1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
  /// 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].
  ///
1421 1422 1423 1424 1425 1426 1427 1428
  /// 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.
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
  ///
  /// 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;

1440
  /// {@template flutter.widgets.ModalRoute.maintainState}
1441 1442 1443 1444 1445 1446 1447
  /// 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.
1448 1449 1450 1451
  ///
  /// 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).
1452
  /// {@endtemplate}
1453
  ///
1454 1455 1456
  /// If this getter would ever start returning a different value, the
  /// [changedInternalState] should be invoked so that the change can take
  /// effect.
1457 1458 1459 1460 1461
  ///
  /// See also:
  ///
  ///  * [OverlayEntry.maintainState], which is the underlying implementation
  ///    of this property.
1462 1463
  bool get maintainState;

1464 1465 1466

  // The API for _ModalScope and HeroController

1467 1468 1469 1470 1471 1472 1473
  /// 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.
1474 1475 1476
  ///
  /// The modal barrier, if any, is not rendered if [offstage] is true (see
  /// [barrierColor]).
1477 1478
  ///
  /// Whenever this changes value, [changedInternalState] is called.
1479 1480
  bool get offstage => _offstage;
  bool _offstage = false;
1481
  set offstage(bool value) {
1482
    if (_offstage == value) {
1483
      return;
1484
    }
1485 1486 1487
    setState(() {
      _offstage = value;
    });
1488 1489
    _animationProxy!.parent = _offstage ? kAlwaysCompleteAnimation : super.animation;
    _secondaryAnimationProxy!.parent = _offstage ? kAlwaysDismissedAnimation : super.secondaryAnimation;
1490
    changedInternalState();
1491 1492
  }

1493
  /// The build context for the subtree containing the primary content of this route.
1494
  BuildContext? get subtreeContext => _subtreeKey.currentContext;
1495

1496
  @override
1497 1498
  Animation<double>? get animation => _animationProxy;
  ProxyAnimation? _animationProxy;
1499 1500

  @override
1501 1502
  Animation<double>? get secondaryAnimation => _secondaryAnimationProxy;
  ProxyAnimation? _secondaryAnimationProxy;
1503

1504 1505
  final List<WillPopCallback> _willPopCallbacks = <WillPopCallback>[];

1506 1507
  final Set<PopEntry> _popEntries = <PopEntry>{};

1508 1509 1510 1511 1512
  /// 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.
1513 1514 1515 1516
  ///
  /// 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
1517
  /// for ModalRoute descendants to collectively define the value of [willPop].
1518 1519 1520
  ///
  /// See also:
  ///
1521 1522 1523 1524 1525
  ///  * [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.
1526 1527 1528 1529
  @Deprecated(
    'Use popDisposition instead. '
    'This feature was deprecated after v3.12.0-1.0.pre.',
  )
1530
  @override
1531
  Future<RoutePopDisposition> willPop() async {
1532
    final _ModalScopeState<T>? scope = _scopeKey.currentState;
1533
    assert(scope != null);
1534
    for (final WillPopCallback callback in List<WillPopCallback>.of(_willPopCallbacks)) {
1535
      if (!await callback()) {
1536
        return RoutePopDisposition.doNotPop;
1537
      }
1538
    }
1539
    return super.willPop();
1540 1541
  }

1542 1543 1544
  /// Returns [RoutePopDisposition.doNotPop] if any of the [PopEntry] instances
  /// registered with [registerPopEntry] have [PopEntry.canPopNotifier] set to
  /// false.
1545
  ///
1546 1547 1548 1549 1550
  /// Typically this method is not overridden because applications usually
  /// don't create modal routes directly, they use higher level primitives
  /// like [showDialog]. The scoped [PopEntry] list makes it possible for
  /// ModalRoute descendants to collectively define the value of
  /// [popDisposition].
1551
  ///
1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
  /// See also:
  ///
  ///  * [Form], which provides an `onPopInvoked` callback that is similar.
  ///  * [registerPopEntry], which adds a [PopEntry] to the list this method
  ///    checks.
  ///  * [unregisterPopEntry], which removes a [PopEntry] from the list this
  ///    method checks.
  @override
  RoutePopDisposition get popDisposition {
    final bool canPop = _popEntries.every((PopEntry popEntry) {
      return popEntry.canPopNotifier.value;
    });

    if (!canPop) {
      return RoutePopDisposition.doNotPop;
    }
    return super.popDisposition;
  }

  @override
  void onPopInvoked(bool didPop) {
    for (final PopEntry popEntry in _popEntries) {
      popEntry.onPopInvoked?.call(didPop);
    }
  }

  /// Enables this route to veto attempts by the user to dismiss it.
1579 1580
  ///
  /// This callback runs asynchronously and it's possible that it will be called
1581
  /// after its route has been disposed. The callback should check [State.mounted]
1582 1583 1584 1585 1586 1587
  /// 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.
  ///
1588 1589
  /// See also:
  ///
1590 1591 1592 1593 1594 1595
  ///  * [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.
1596 1597 1598 1599
  @Deprecated(
    'Use registerPopEntry or PopScope instead. '
    'This feature was deprecated after v3.12.0-1.0.pre.',
  )
1600
  void addScopedWillPopCallback(WillPopCallback callback) {
1601 1602
    assert(_scopeKey.currentState != null, 'Tried to add a willPop callback to a route that is not currently in the tree.');
    _willPopCallbacks.add(callback);
1603 1604 1605 1606 1607 1608
  }

  /// Remove one of the callbacks run by [willPop].
  ///
  /// See also:
  ///
1609 1610 1611
  ///  * [Form], which provides an `onWillPop` callback that uses this mechanism.
  ///  * [addScopedWillPopCallback], which adds callback to the list
  ///    checked by [willPop].
1612 1613 1614 1615
  @Deprecated(
    'Use unregisterPopEntry or PopScope instead. '
    'This feature was deprecated after v3.12.0-1.0.pre.',
  )
1616
  void removeScopedWillPopCallback(WillPopCallback callback) {
1617 1618
    assert(_scopeKey.currentState != null, 'Tried to remove a willPop callback from a route that is not currently in the tree.');
    _willPopCallbacks.remove(callback);
1619 1620
  }

1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674
  /// Registers the existence of a [PopEntry] in the route.
  ///
  /// [PopEntry] instances registered in this way will have their
  /// [PopEntry.onPopInvoked] callbacks called when a route is popped or a pop
  /// is attempted. They will also be able to block pop operations with
  /// [PopEntry.canPopNotifier] through this route's [popDisposition] method.
  ///
  /// See also:
  ///
  ///  * [unregisterPopEntry], which performs the opposite operation.
  void registerPopEntry(PopEntry popEntry) {
    _popEntries.add(popEntry);
    popEntry.canPopNotifier.addListener(_handlePopEntryChange);
    _handlePopEntryChange();
  }

  /// Unregisters a [PopEntry] in the route's widget subtree.
  ///
  /// See also:
  ///
  ///  * [registerPopEntry], which performs the opposite operation.
  void unregisterPopEntry(PopEntry popEntry) {
    _popEntries.remove(popEntry);
    popEntry.canPopNotifier.removeListener(_handlePopEntryChange);
    _handlePopEntryChange();
  }

  void _handlePopEntryChange() {
    if (!isCurrent) {
      return;
    }
    final NavigationNotification notification = NavigationNotification(
      // canPop indicates that the originator of the Notification can handle a
      // pop. In the case of PopScope, it handles pops when canPop is
      // false. Hence the seemingly backward logic here.
      canHandlePop: popDisposition == RoutePopDisposition.doNotPop,
    );
    // Avoid dispatching a notification in the middle of a build.
    switch (SchedulerBinding.instance.schedulerPhase) {
      case SchedulerPhase.postFrameCallbacks:
        notification.dispatch(subtreeContext);
      case SchedulerPhase.idle:
      case SchedulerPhase.midFrameMicrotasks:
      case SchedulerPhase.persistentCallbacks:
      case SchedulerPhase.transientCallbacks:
        SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) {
          if (!(subtreeContext?.mounted ?? false)) {
            return;
          }
          notification.dispatch(subtreeContext);
        });
    }
  }

1675 1676
  /// True if one or more [WillPopCallback] callbacks exist.
  ///
1677 1678 1679 1680
  /// 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.
1681
  ///
1682 1683 1684 1685
  /// 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.
  ///
1686 1687
  /// See also:
  ///
1688 1689 1690 1691
  ///  * [addScopedWillPopCallback], which adds a callback.
  ///  * [removeScopedWillPopCallback], which removes a callback.
  ///  * [willHandlePopInternally], which reports on another reason why
  ///    a pop might be vetoed.
1692 1693 1694 1695
  @Deprecated(
    'Use popDisposition instead. '
    'This feature was deprecated after v3.12.0-1.0.pre.',
  )
1696
  @protected
1697
  bool get hasScopedWillPopCallback {
1698 1699 1700 1701
    return _willPopCallbacks.isNotEmpty;
  }

  @override
1702
  void didChangePrevious(Route<dynamic>? previousRoute) {
1703 1704
    super.didChangePrevious(previousRoute);
    changedInternalState();
1705
  }
1706

1707 1708 1709
  @override
  void changedInternalState() {
    super.changedInternalState();
1710 1711
    setState(() { /* internal state already changed */ });
    _modalBarrier.markNeedsBuild();
1712
    _modalScope.maintainState = maintainState;
1713 1714 1715
  }

  @override
1716 1717
  void changedExternalState() {
    super.changedExternalState();
1718
    _modalBarrier.markNeedsBuild();
1719
    if (_scopeKey.currentState != null) {
1720
      _scopeKey.currentState!._forceRebuildPage();
1721
    }
1722 1723 1724 1725
  }

  /// Whether this route can be popped.
  ///
1726 1727 1728
  /// A route can be popped if there is at least one active route below it, or
  /// if [willHandlePopInternally] returns true.
  ///
1729 1730 1731
  /// When this changes, if the route is visible, the route will
  /// rebuild, and any widgets that used [ModalRoute.of] will be
  /// notified.
1732
  bool get canPop => hasActiveRouteBelow || willHandlePopInternally;
1733

1734 1735 1736 1737
  /// 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,
1738
  /// or there is at least one [LocalHistoryEntry] with [impliesAppBarDismissal]
1739 1740 1741
  /// set to true
  bool get impliesAppBarDismissal => hasActiveRouteBelow || _entriesImpliesAppBarDismissal > 0;

1742 1743
  // Internals

1744 1745 1746
  final GlobalKey<_ModalScopeState<T>> _scopeKey = GlobalKey<_ModalScopeState<T>>();
  final GlobalKey _subtreeKey = GlobalKey();
  final PageStorageBucket _storageBucket = PageStorageBucket();
1747

1748
  // one of the builders
1749
  late OverlayEntry _modalBarrier;
1750
  Widget _buildModalBarrier(BuildContext context) {
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781
    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() {
1782
    Widget barrier;
1783
    if (barrierColor != null && barrierColor!.alpha != 0 && !offstage) { // changedInternalState is called if barrierColor or offstage updates
1784
      assert(barrierColor != barrierColor!.withOpacity(0.0));
1785
      final Animation<Color?> color = animation!.drive(
1786
        ColorTween(
1787
          begin: barrierColor!.withOpacity(0.0),
1788 1789
          end: barrierColor, // changedInternalState is called if barrierColor updates
        ).chain(CurveTween(curve: barrierCurve)), // changedInternalState is called if barrierCurve updates
1790
      );
1791
      barrier = AnimatedModalBarrier(
1792
        color: color,
1793 1794
        dismissible: barrierDismissible, // changedInternalState is called if barrierDismissible updates
        semanticsLabel: barrierLabel, // changedInternalState is called if barrierLabel updates
1795
        barrierSemanticsDismissible: semanticsDismissible,
Hixie's avatar
Hixie committed
1796 1797
      );
    } else {
1798
      barrier = ModalBarrier(
1799 1800
        dismissible: barrierDismissible, // changedInternalState is called if barrierDismissible updates
        semanticsLabel: barrierLabel, // changedInternalState is called if barrierLabel updates
1801
        barrierSemanticsDismissible: semanticsDismissible,
1802
      );
Hixie's avatar
Hixie committed
1803
    }
1804

1805
    return barrier;
1806 1807
  }

1808 1809
  // 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.
1810
  Widget? _modalScopeCache;
1811

1812
  // one of the builders
1813
  Widget _buildModalScope(BuildContext context) {
1814 1815 1816 1817 1818 1819 1820
    // 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
1821
      ),
1822 1823 1824
    );
  }

1825
  late OverlayEntry _modalScope;
1826

1827
  @override
1828 1829 1830 1831 1832
  Iterable<OverlayEntry> createOverlayEntries() {
    return <OverlayEntry>[
      _modalBarrier = OverlayEntry(builder: _buildModalBarrier),
      _modalScope = OverlayEntry(builder: _buildModalScope, maintainState: maintainState),
    ];
1833
  }
1834

1835
  @override
1836
  String toString() => '${objectRuntimeType(this, 'ModalRoute')}($settings, animation: $_animation)';
1837
}
Hixie's avatar
Hixie committed
1838 1839

/// A modal route that overlays a widget over the current route.
1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852
///
/// {@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
1853
abstract class PopupRoute<T> extends ModalRoute<T> {
1854 1855
  /// Initializes the [PopupRoute].
  PopupRoute({
1856 1857
    super.settings,
    super.filter,
1858
    super.traversalEdgeBehavior,
1859
  });
1860

1861
  @override
Hixie's avatar
Hixie committed
1862
  bool get opaque => false;
1863

1864 1865
  @override
  bool get maintainState => true;
1866 1867

  @override
1868
  bool get allowSnapshotting => false;
Hixie's avatar
Hixie committed
1869
}
1870 1871 1872 1873

/// A [Navigator] observer that notifies [RouteAware]s of changes to the
/// state of their [Route].
///
1874 1875 1876
/// [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>`
1877 1878 1879
/// will inform subscribed [RouteAware]s whenever the user navigates away from
/// the current page route to another page route.
///
1880 1881 1882 1883 1884
/// To be informed about route changes of any type, consider instantiating a
/// `RouteObserver<Route>`.
///
/// ## Type arguments
///
1885 1886 1887
/// 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
1888 1889
/// be given with their type arguments. Since the [Route] class and its
/// subclasses have a type argument, this includes the arguments passed to this
1890
/// class. Consider using `dynamic` to specify the entire class of routes rather
1891
/// than only specific subtypes. For example, to watch for all [ModalRoute]
1892
/// variants, the `RouteObserver<ModalRoute<dynamic>>` type may be used.
1893
///
1894
/// {@tool snippet}
1895
///
1896
/// To make a [StatefulWidget] aware of its current [Route] state, implement
1897
/// [RouteAware] in its [State] and subscribe it to a [RouteObserver]:
1898 1899
///
/// ```dart
1900
/// // Register the RouteObserver as a navigation observer.
1901
/// final RouteObserver<ModalRoute<void>> routeObserver = RouteObserver<ModalRoute<void>>();
1902
///
1903
/// void main() {
1904 1905
///   runApp(MaterialApp(
///     home: Container(),
1906
///     navigatorObservers: <RouteObserver<ModalRoute<void>>>[ routeObserver ],
1907 1908 1909 1910
///   ));
/// }
///
/// class RouteAwareWidget extends StatefulWidget {
1911
///   const RouteAwareWidget({super.key});
1912 1913
///
///   @override
1914
///   State<RouteAwareWidget> createState() => RouteAwareWidgetState();
1915 1916 1917
/// }
///
/// // Implement RouteAware in a widget's state and subscribe it to the RouteObserver.
1918
/// class RouteAwareWidgetState extends State<RouteAwareWidget> with RouteAware {
1919
///
1920 1921 1922
///   @override
///   void didChangeDependencies() {
///     super.didChangeDependencies();
1923
///     routeObserver.subscribe(this, ModalRoute.of(context)!);
1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
///   }
///
///   @override
///   void dispose() {
///     routeObserver.unsubscribe(this);
///     super.dispose();
///   }
///
///   @override
///   void didPush() {
1934
///     // Route was pushed onto navigator and is now topmost route.
1935 1936 1937 1938
///   }
///
///   @override
///   void didPopNext() {
1939
///     // Covering route was popped off the navigator.
1940 1941
///   }
///
1942
///   @override
1943
///   Widget build(BuildContext context) => Container();
1944
///
1945 1946
/// }
/// ```
1947
/// {@end-tool}
1948
class RouteObserver<R extends Route<dynamic>> extends NavigatorObserver {
1949
  final Map<R, Set<RouteAware>> _listeners = <R, Set<RouteAware>>{};
1950

1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
  /// 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;
  }

1964 1965 1966 1967 1968
  /// 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.
1969
  void subscribe(RouteAware routeAware, R route) {
1970
    final Set<RouteAware> subscribers = _listeners.putIfAbsent(route, () => <RouteAware>{});
1971
    if (subscribers.add(routeAware)) {
1972 1973 1974 1975
      routeAware.didPush();
    }
  }

1976 1977
  /// Unsubscribe [routeAware].
  ///
1978 1979
  /// [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.
1980
  void unsubscribe(RouteAware routeAware) {
1981 1982
    final List<R> routes = _listeners.keys.toList();
    for (final R route in routes) {
1983
      final Set<RouteAware>? subscribers = _listeners[route];
1984 1985 1986 1987 1988 1989
      if (subscribers != null) {
        subscribers.remove(routeAware);
        if (subscribers.isEmpty) {
          _listeners.remove(route);
        }
      }
1990
    }
1991 1992 1993
  }

  @override
1994
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
1995
    if (route is R && previousRoute is R) {
1996
      final List<RouteAware>? previousSubscribers = _listeners[previousRoute]?.toList();
1997 1998

      if (previousSubscribers != null) {
1999
        for (final RouteAware routeAware in previousSubscribers) {
2000 2001 2002 2003
          routeAware.didPopNext();
        }
      }

2004
      final List<RouteAware>? subscribers = _listeners[route]?.toList();
2005 2006

      if (subscribers != null) {
2007
        for (final RouteAware routeAware in subscribers) {
2008 2009 2010
          routeAware.didPop();
        }
      }
2011 2012 2013 2014
    }
  }

  @override
2015
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
2016
    if (route is R && previousRoute is R) {
2017
      final Set<RouteAware>? previousSubscribers = _listeners[previousRoute];
2018 2019

      if (previousSubscribers != null) {
2020
        for (final RouteAware routeAware in previousSubscribers) {
2021 2022 2023
          routeAware.didPushNext();
        }
      }
2024 2025 2026 2027
    }
  }
}

2028 2029 2030 2031
/// 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.
2032
abstract mixin class RouteAware {
2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045
  /// 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() { }
2046
}
2047

2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069
/// 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.
///
2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
/// {@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}
///
2085 2086
/// See also:
///
2087 2088
///  * [DisplayFeatureSubScreen], which documents the specifics of how
///    [DisplayFeature]s can split the screen into sub-screens.
2089 2090 2091 2092 2093 2094
///  * [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({
2095
    required RoutePageBuilder pageBuilder,
2096
    bool barrierDismissible = true,
2097
    Color? barrierColor = const Color(0x80000000),
2098
    String? barrierLabel,
2099
    Duration transitionDuration = const Duration(milliseconds: 200),
2100
    RouteTransitionsBuilder? transitionBuilder,
2101
    super.settings,
2102
    this.anchorPoint,
2103
    super.traversalEdgeBehavior,
2104
  }) : _pageBuilder = pageBuilder,
2105 2106 2107 2108
       _barrierDismissible = barrierDismissible,
       _barrierLabel = barrierLabel,
       _barrierColor = barrierColor,
       _transitionDuration = transitionDuration,
2109
       _transitionBuilder = transitionBuilder;
2110 2111 2112 2113 2114 2115 2116 2117

  final RoutePageBuilder _pageBuilder;

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

  @override
2118 2119
  String? get barrierLabel => _barrierLabel;
  final String? _barrierLabel;
2120 2121

  @override
2122 2123
  Color? get barrierColor => _barrierColor;
  final Color? _barrierColor;
2124 2125 2126 2127 2128

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

2129
  final RouteTransitionsBuilder? _transitionBuilder;
2130

2131 2132 2133
  /// {@macro flutter.widgets.DisplayFeatureSubScreen.anchorPoint}
  final Offset? anchorPoint;

2134 2135
  @override
  Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
2136
    return Semantics(
2137 2138
      scopesRoute: true,
      explicitChildNodes: true,
2139 2140 2141 2142
      child: DisplayFeatureSubScreen(
        anchorPoint: anchorPoint,
        child: _pageBuilder(context, animation, secondaryAnimation),
      ),
2143 2144 2145 2146 2147 2148
    );
  }

  @override
  Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
    if (_transitionBuilder == null) {
2149
      // Some default transition.
2150
      return FadeTransition(
2151 2152 2153 2154 2155 2156
        opacity: CurvedAnimation(
          parent: animation,
          curve: Curves.linear,
        ),
        child: child,
      );
2157
    }
2158
    return _transitionBuilder(context, animation, secondaryAnimation, child);
2159 2160 2161 2162 2163 2164 2165 2166 2167 2168
  }
}

/// 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`
2169
/// does not share a context with the location that [showGeneralDialog] is
2170
/// originally called from. Use a [StatefulBuilder] or a custom
2171
/// [StatefulWidget] if the dialog needs to update dynamically.
2172
///
2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184
/// 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)`.
2185 2186 2187
///
/// The `barrierDismissible` argument is used to determine whether this route
/// can be dismissed by tapping the modal barrier. This argument defaults
2188
/// to false. If `barrierDismissible` is true, a non-null `barrierLabel` must be
2189 2190 2191
/// provided.
///
/// The `barrierLabel` argument is the semantic label used for a dismissible
2192
/// barrier. This argument defaults to `null`.
2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
///
/// 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.
///
2205 2206 2207
/// The `routeSettings` will be used in the construction of the dialog's route.
/// See [RouteSettings] for more details.
///
2208 2209
/// {@macro flutter.widgets.RawDialogRoute}
///
2210 2211 2212
/// Returns a [Future] that resolves to the value (if any) that was passed to
/// [Navigator.pop] when the dialog was closed.
///
2213 2214 2215 2216 2217 2218 2219 2220
/// ### 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].
///
2221
/// {@tool sample}
2222 2223 2224 2225 2226 2227 2228
/// 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}
///
2229
/// ** See code in examples/api/lib/widgets/routes/show_general_dialog.0.dart **
2230 2231
/// {@end-tool}
///
2232
/// See also:
2233
///
2234 2235
///  * [DisplayFeatureSubScreen], which documents the specifics of how
///    [DisplayFeature]s can split the screen into sub-screens.
2236 2237
///  * [showDialog], which displays a Material-style dialog.
///  * [showCupertinoDialog], which displays an iOS-style dialog.
2238
Future<T?> showGeneralDialog<T extends Object?>({
2239 2240
  required BuildContext context,
  required RoutePageBuilder pageBuilder,
2241
  bool barrierDismissible = false,
2242
  String? barrierLabel,
2243 2244
  Color barrierColor = const Color(0x80000000),
  Duration transitionDuration = const Duration(milliseconds: 200),
2245
  RouteTransitionsBuilder? transitionBuilder,
2246
  bool useRootNavigator = true,
2247
  RouteSettings? routeSettings,
2248
  Offset? anchorPoint,
2249 2250
}) {
  assert(!barrierDismissible || barrierLabel != null);
2251
  return Navigator.of(context, rootNavigator: useRootNavigator).push<T>(RawDialogRoute<T>(
2252 2253 2254 2255 2256 2257
    pageBuilder: pageBuilder,
    barrierDismissible: barrierDismissible,
    barrierLabel: barrierLabel,
    barrierColor: barrierColor,
    transitionDuration: transitionDuration,
    transitionBuilder: transitionBuilder,
2258
    settings: routeSettings,
2259
    anchorPoint: anchorPoint,
2260 2261 2262 2263 2264 2265 2266
  ));
}

/// 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.
2267
typedef RoutePageBuilder = Widget Function(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation);
2268 2269 2270 2271 2272

/// Signature for the function that builds a route's transitions.
/// Used in [PageRouteBuilder] and [showGeneralDialog].
///
/// See [ModalRoute.buildTransitions] for complete definition of the parameters.
2273
typedef RouteTransitionsBuilder = Widget Function(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child);
2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303

/// A callback type for informing that a navigation pop has been invoked,
/// whether or not it was handled successfully.
///
/// Accepts a didPop boolean indicating whether or not back navigation
/// succeeded.
typedef PopInvokedCallback = void Function(bool didPop);

/// Allows listening to and preventing pops.
///
/// Can be registered in [ModalRoute] to listen to pops with [onPopInvoked] or
/// to enable/disable them with [canPopNotifier].
///
/// See also:
///
///  * [PopScope], which provides similar functionality in a widget.
///  * [ModalRoute.registerPopEntry], which unregisters instances of this.
///  * [ModalRoute.unregisterPopEntry], which unregisters instances of this.
abstract class PopEntry {
  /// {@macro flutter.widgets.PopScope.onPopInvoked}
  PopInvokedCallback? get onPopInvoked;

  /// {@macro flutter.widgets.PopScope.canPop}
  ValueListenable<bool> get canPopNotifier;

  @override
  String toString() {
    return 'PopEntry canPop: ${canPopNotifier.value}, onPopInvoked: $onPopInvoked';
  }
}