routes.dart 82.9 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 10
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
11
import 'package:flutter/scheduler.dart';
12
import 'package:flutter/services.dart';
13

14
import 'actions.dart';
Adam Barth's avatar
Adam Barth committed
15
import 'basic.dart';
16
import 'display_feature_sub_screen.dart';
17 18
import 'focus_manager.dart';
import 'focus_scope.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 30
// Examples can assume:
// dynamic routeObserver;
31
// late NavigatorState navigator;
32 33 34
// late BuildContext context;
// Future<bool> askTheUserIfTheyAreSure() async { return true; }
// abstract class MyWidget extends StatefulWidget { const MyWidget({Key? key}) : super(key: key); }
35

36
/// A route that displays widgets in the [Navigator]'s [Overlay].
Hixie's avatar
Hixie committed
37
abstract class OverlayRoute<T> extends Route<T> {
38 39
  /// Creates a route that knows how to interact with an [Overlay].
  OverlayRoute({
40
    RouteSettings? settings,
41 42
  }) : super(settings: settings);

43
  /// Subclasses should override this getter to return the builders for the overlay.
44
  @factory
45
  Iterable<OverlayEntry> createOverlayEntries();
Adam Barth's avatar
Adam Barth committed
46

47
  @override
Adam Barth's avatar
Adam Barth committed
48
  List<OverlayEntry> get overlayEntries => _overlayEntries;
49
  final List<OverlayEntry> _overlayEntries = <OverlayEntry>[];
Adam Barth's avatar
Adam Barth committed
50

51
  @override
52
  void install() {
53
    assert(_overlayEntries.isEmpty);
54
    _overlayEntries.addAll(createOverlayEntries());
55
    super.install();
Adam Barth's avatar
Adam Barth committed
56 57
  }

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

70
  @override
71
  bool didPop(T? result) {
72 73
    final bool returnValue = super.didPop(result);
    assert(returnValue);
74
    if (finishedWhenPopped)
75
      navigator!.finalizeRoute(this);
76
    return returnValue;
Hixie's avatar
Hixie committed
77 78
  }

79 80
  @override
  void dispose() {
Adam Barth's avatar
Adam Barth committed
81
    _overlayEntries.clear();
82
    super.dispose();
83
  }
Adam Barth's avatar
Adam Barth committed
84 85
}

86
/// A route with entrance and exit transitions.
Hixie's avatar
Hixie committed
87
abstract class TransitionRoute<T> extends OverlayRoute<T> {
88 89
  /// Creates a route that animates itself when it is pushed or popped.
  TransitionRoute({
90
    RouteSettings? settings,
91 92
  }) : super(settings: settings);

Hixie's avatar
Hixie committed
93 94
  /// This future completes only once the transition itself has finished, after
  /// the overlay entries have been removed from the navigator's overlay.
95 96
  ///
  /// This future completes once the animation has been dismissed. That will be
97 98
  /// after [popped], because [popped] typically completes before the animation
  /// even starts, as soon as the route is popped.
99 100
  Future<T?> get completed => _transitionCompleter.future;
  final Completer<T?> _transitionCompleter = Completer<T?>();
101

102
  /// {@template flutter.widgets.TransitionRoute.transitionDuration}
103 104 105 106 107 108
  /// The duration the transition going forwards.
  ///
  /// See also:
  ///
  /// * [reverseTransitionDuration], which controls the duration of the
  /// transition when it is in reverse.
109
  /// {@endtemplate}
Adam Barth's avatar
Adam Barth committed
110
  Duration get transitionDuration;
111

112
  /// {@template flutter.widgets.TransitionRoute.reverseTransitionDuration}
113 114 115 116
  /// The duration the transition going in reverse.
  ///
  /// By default, the reverse transition duration is set to the value of
  /// the forwards [transitionDuration].
117
  /// {@endtemplate}
118 119
  Duration get reverseTransitionDuration => transitionDuration;

120
  /// {@template flutter.widgets.TransitionRoute.opaque}
121 122 123 124
  /// 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.
125
  /// {@endtemplate}
Adam Barth's avatar
Adam Barth committed
126 127
  bool get opaque;

128 129 130 131
  // 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.
132
  @override
133 134 135
  bool get finishedWhenPopped => _controller!.status == AnimationStatus.dismissed && !_popFinalized;

  bool _popFinalized = false;
136

137 138
  /// The animation that drives the route's transition and the previous route's
  /// forward transition.
139 140
  Animation<double>? get animation => _animation;
  Animation<double>? _animation;
141

142 143 144
  /// The animation controller that the route uses to drive the transitions.
  ///
  /// The animation itself is exposed by the [animation] property.
145
  @protected
146 147
  AnimationController? get controller => _controller;
  AnimationController? _controller;
148

149 150 151
  /// 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.
152
  Animation<double>? get secondaryAnimation => _secondaryAnimation;
153 154
  final ProxyAnimation _secondaryAnimation = ProxyAnimation(kAlwaysDismissedAnimation);

155 156 157 158 159 160 161 162 163
  /// 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;

164
  /// Called to create the animation controller that will drive the transitions to
165 166
  /// this route from the previous one, and back to the previous route from this
  /// one.
167 168 169
  ///
  /// The returned controller will be disposed by [AnimationController.dispose]
  /// if the [willDisposeAnimationController] is `true`.
170
  AnimationController createAnimationController() {
171
    assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
172
    final Duration duration = transitionDuration;
173
    final Duration reverseDuration = reverseTransitionDuration;
174
    assert(duration != null && duration >= Duration.zero);
175
    return AnimationController(
176
      duration: duration,
177
      reverseDuration: reverseDuration,
178
      debugLabel: debugLabel,
179
      vsync: navigator!,
180
    );
Adam Barth's avatar
Adam Barth committed
181 182
  }

183 184
  /// Called to create the animation that exposes the current progress of
  /// the transition controlled by the animation controller created by
185
  /// [createAnimationController()].
186
  Animation<double> createAnimation() {
187
    assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
188
    assert(_controller != null);
189
    return _controller!.view;
190 191
  }

192
  T? _result;
Adam Barth's avatar
Adam Barth committed
193

194
  void _handleStatusChanged(AnimationStatus status) {
Adam Barth's avatar
Adam Barth committed
195
    switch (status) {
196
      case AnimationStatus.completed:
Adam Barth's avatar
Adam Barth committed
197 198 199
        if (overlayEntries.isNotEmpty)
          overlayEntries.first.opaque = opaque;
        break;
200 201
      case AnimationStatus.forward:
      case AnimationStatus.reverse:
Adam Barth's avatar
Adam Barth committed
202 203 204
        if (overlayEntries.isNotEmpty)
          overlayEntries.first.opaque = false;
        break;
205
      case AnimationStatus.dismissed:
206
        // We might still be an active route if a subclass is controlling the
Pierre-Louis's avatar
Pierre-Louis committed
207
        // transition and hits the dismissed status. For example, the iOS
208
        // back gesture drives this animation to the dismissed status before
209 210
        // removing the route and disposing it.
        if (!isActive) {
211
          navigator!.finalizeRoute(this);
212
          _popFinalized = true;
213
        }
Adam Barth's avatar
Adam Barth committed
214 215 216 217
        break;
    }
  }

218
  @override
219
  void install() {
220
    assert(!_transitionCompleter.isCompleted, 'Cannot install a $runtimeType after disposing it.');
221
    _controller = createAnimationController();
222
    assert(_controller != null, '$runtimeType.createAnimationController() returned null.');
223 224
    _animation = createAnimation()
      ..addStatusListener(_handleStatusChanged);
225
    assert(_animation != null, '$runtimeType.createAnimation() returned null.');
226
    super.install();
227
    if (_animation!.isCompleted && overlayEntries.isNotEmpty) {
228 229
      overlayEntries.first.opaque = opaque;
    }
230 231
  }

232
  @override
233
  TickerFuture didPush() {
234 235
    assert(_controller != null, '$runtimeType.didPush called before calling install() or after calling dispose().');
    assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
236
    super.didPush();
237
    return _controller!.forward();
Adam Barth's avatar
Adam Barth committed
238 239
  }

240 241 242 243 244
  @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();
245
    _controller!.value = _controller!.upperBound;
246 247
  }

248
  @override
249
  void didReplace(Route<dynamic>? oldRoute) {
250 251
    assert(_controller != null, '$runtimeType.didReplace called before calling install() or after calling dispose().');
    assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
252
    if (oldRoute is TransitionRoute)
253
      _controller!.value = oldRoute._controller!.value;
254 255 256
    super.didReplace(oldRoute);
  }

257
  @override
258
  bool didPop(T? result) {
259 260
    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
261
    _result = result;
262
    _controller!.reverse();
263
    return super.didPop(result);
Hixie's avatar
Hixie committed
264 265
  }

266
  @override
267
  void didPopNext(Route<dynamic> nextRoute) {
268 269
    assert(_controller != null, '$runtimeType.didPopNext called before calling install() or after calling dispose().');
    assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
270
    _updateSecondaryAnimation(nextRoute);
Hixie's avatar
Hixie committed
271
    super.didPopNext(nextRoute);
Adam Barth's avatar
Adam Barth committed
272 273
  }

274
  @override
275
  void didChangeNext(Route<dynamic>? nextRoute) {
276 277
    assert(_controller != null, '$runtimeType.didChangeNext called before calling install() or after calling dispose().');
    assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
278
    _updateSecondaryAnimation(nextRoute);
Hixie's avatar
Hixie committed
279
    super.didChangeNext(nextRoute);
280 281
  }

282 283 284 285 286
  // 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.
287
  VoidCallback? _trainHoppingListenerRemover;
288

289
  void _updateSecondaryAnimation(Route<dynamic>? nextRoute) {
290 291 292
    // There is an existing train hopping in progress. Unfortunately, we cannot
    // dispose current train hopping animation until we replace it with a new
    // animation.
293
    final VoidCallback? previousTrainHoppingListenerRemover = _trainHoppingListenerRemover;
294 295
    _trainHoppingListenerRemover = null;

296
    if (nextRoute is TransitionRoute<dynamic> && canTransitionTo(nextRoute) && nextRoute.canTransitionFrom(this)) {
297
      final Animation<double>? current = _secondaryAnimation.parent;
Hixie's avatar
Hixie committed
298
      if (current != null) {
299 300
        final Animation<double> currentTrain = (current is TrainHoppingAnimation ? current.currentTrain : current)!;
        final Animation<double> nextTrain = nextRoute._animation!;
301 302 303 304 305
        if (
          currentTrain.value == nextTrain.value ||
          nextTrain.status == AnimationStatus.completed ||
          nextTrain.status == AnimationStatus.dismissed
        ) {
306 307
          _setSecondaryAnimation(nextTrain, nextRoute.completed);
        } else {
308 309 310 311 312 313 314 315 316 317
          // 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.
318
          TrainHoppingAnimation? newAnimation;
319 320 321 322 323 324 325 326 327
          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);
                if (_trainHoppingListenerRemover != null) {
328
                  _trainHoppingListenerRemover!();
329 330 331 332 333 334 335 336 337 338 339 340 341
                  _trainHoppingListenerRemover = null;
                }
                break;
              case AnimationStatus.forward:
              case AnimationStatus.reverse:
                break;
            }
          }
          _trainHoppingListenerRemover = () {
            nextTrain.removeStatusListener(_jumpOnAnimationEnd);
            newAnimation?.dispose();
          };
          nextTrain.addStatusListener(_jumpOnAnimationEnd);
342
          newAnimation = TrainHoppingAnimation(
343 344
            currentTrain,
            nextTrain,
Hixie's avatar
Hixie committed
345
            onSwitchedTrain: () {
346
              assert(_secondaryAnimation.parent == newAnimation);
347
              assert(newAnimation!.currentTrain == nextRoute._animation);
348 349
              // We can hop on the nextTrain, so we don't need to listen to
              // whether the nextTrain has stopped.
350
              _setSecondaryAnimation(newAnimation!.currentTrain, nextRoute.completed);
351
              if (_trainHoppingListenerRemover != null) {
352
                _trainHoppingListenerRemover!();
353 354
                _trainHoppingListenerRemover = null;
              }
355
            },
Hixie's avatar
Hixie committed
356
          );
357 358
          _setSecondaryAnimation(newAnimation, nextRoute.completed);
        }
Hixie's avatar
Hixie committed
359
      } else {
360
        _setSecondaryAnimation(nextRoute._animation, nextRoute.completed);
Hixie's avatar
Hixie committed
361
      }
Hixie's avatar
Hixie committed
362
    } else {
363
      _setSecondaryAnimation(kAlwaysDismissedAnimation);
Hixie's avatar
Hixie committed
364
    }
365 366 367 368 369
    // 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
370 371
  }

372
  void _setSecondaryAnimation(Animation<double>? animation, [Future<dynamic>? disposed]) {
373
    _secondaryAnimation.parent = animation;
374
    // Releases the reference to the next route's animation when that route
375
    // is disposed.
376
    disposed?.then((dynamic _) {
377 378 379 380 381 382 383 384 385
      if (_secondaryAnimation.parent == animation) {
        _secondaryAnimation.parent = kAlwaysDismissedAnimation;
        if (animation is TrainHoppingAnimation) {
          animation.dispose();
        }
      }
    });
  }

386 387 388
  /// 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.
389
  ///
390
  /// Subclasses can override this method to restrict the set of routes they
391
  /// need to coordinate transitions with.
392 393
  ///
  /// If true, and `nextRoute.canTransitionFrom()` is true, then the
394
  /// [ModalRoute.buildTransitions] `secondaryAnimation` will run from 0.0 - 1.0
395 396 397 398
  /// when [nextRoute] is pushed on top of this one.  Similarly, if
  /// the [nextRoute] is popped off of this route, the
  /// `secondaryAnimation` will run from 1.0 - 0.0.
  ///
399
  /// If false, this route's [ModalRoute.buildTransitions] `secondaryAnimation` parameter
400
  /// value will be [kAlwaysDismissedAnimation]. In other words, this route
nt4f04uNd's avatar
nt4f04uNd committed
401
  /// will not animate when [nextRoute] is pushed on top of it or when
402 403 404 405 406 407 408
  /// [nextRoute] is popped off of it.
  ///
  /// Returns true by default.
  ///
  /// See also:
  ///
  ///  * [canTransitionFrom], which must be true for [nextRoute] for the
409
  ///    [ModalRoute.buildTransitions] `secondaryAnimation` to run.
410
  bool canTransitionTo(TransitionRoute<dynamic> nextRoute) => true;
411

412 413
  /// 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.
414
  ///
415
  /// Subclasses can override this method to restrict the set of routes they
416
  /// need to coordinate transitions with.
417 418
  ///
  /// If true, and `previousRoute.canTransitionTo()` is true, then the
419
  /// previous route's [ModalRoute.buildTransitions] `secondaryAnimation` will
420 421 422 423
  /// 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.
  ///
424
  /// If false, then the previous route's [ModalRoute.buildTransitions]
425 426 427 428 429 430 431 432 433
  /// `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
434
  ///    [ModalRoute.buildTransitions] `secondaryAnimation` to run.
435
  bool canTransitionFrom(TransitionRoute<dynamic> previousRoute) => true;
436

437
  @override
Hixie's avatar
Hixie committed
438
  void dispose() {
439
    assert(!_transitionCompleter.isCompleted, 'Cannot dispose a $runtimeType twice.');
440
    _animation?.removeStatusListener(_handleStatusChanged);
441 442 443
    if (willDisposeAnimationController) {
      _controller?.dispose();
    }
444
    _transitionCompleter.complete(_result);
Hixie's avatar
Hixie committed
445 446 447
    super.dispose();
  }

448
  /// A short description of this route useful for debugging.
449
  String get debugLabel => objectRuntimeType(this, 'TransitionRoute');
450 451

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

455
/// An entry in the history of a [LocalHistoryRoute].
Hixie's avatar
Hixie committed
456
class LocalHistoryEntry {
457
  /// Creates an entry in the history of a [LocalHistoryRoute].
Hixie's avatar
Hixie committed
458
  LocalHistoryEntry({ this.onRemove });
459 460

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

463
  LocalHistoryRoute<dynamic>? _owner;
464 465

  /// Remove this entry from the history of its associated [LocalHistoryRoute].
Hixie's avatar
Hixie committed
466
  void remove() {
467
    _owner?.removeLocalHistoryEntry(this);
468
    assert(_owner == null);
Hixie's avatar
Hixie committed
469
  }
470

Hixie's avatar
Hixie committed
471
  void _notifyRemoved() {
472
    onRemove?.call();
Hixie's avatar
Hixie committed
473 474 475
  }
}

476
/// A mixin used by routes to handle back navigations internally by popping a list.
477 478
///
/// When a [Navigator] is instructed to pop, the current route is given an
479
/// opportunity to handle the pop internally. A `LocalHistoryRoute` handles the
480 481
/// pop internally if its list of local history entries is non-empty. Rather
/// than being removed as the current route, the most recent [LocalHistoryEntry]
482
/// is removed from the list and its [LocalHistoryEntry.onRemove] is called.
483
mixin LocalHistoryRoute<T> on Route<T> {
484
  List<LocalHistoryEntry>? _localHistory;
485 486 487

  /// Adds a local history entry to this route.
  ///
488
  /// When asked to pop, if this route has any local history entries, this route
489 490 491 492 493
  /// 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.
494
  ///
495
  /// {@tool snippet}
496 497 498 499 500 501 502 503 504 505 506 507 508 509
  ///
  /// 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 {
510 511
  ///   const App({Key? key}) : super(key: key);
  ///
512 513
  ///   @override
  ///   Widget build(BuildContext context) {
514
  ///     return MaterialApp(
515
  ///       initialRoute: '/',
516 517 518
  ///       routes: <String, WidgetBuilder>{
  ///         '/': (BuildContext context) => const HomePage(),
  ///         '/second_page': (BuildContext context) => const SecondPage(),
519 520 521 522 523 524
  ///       },
  ///     );
  ///   }
  /// }
  ///
  /// class HomePage extends StatefulWidget {
525
  ///   const HomePage({Key? key}) : super(key: key);
526 527
  ///
  ///   @override
528
  ///   State<HomePage> createState() => _HomePageState();
529 530 531 532 533
  /// }
  ///
  /// class _HomePageState extends State<HomePage> {
  ///   @override
  ///   Widget build(BuildContext context) {
534 535
  ///     return Scaffold(
  ///       body: Center(
536 537 538
  ///         child: Column(
  ///           mainAxisSize: MainAxisSize.min,
  ///           children: <Widget>[
539
  ///             const Text('HomePage'),
540
  ///             // Press this button to open the SecondPage.
541
  ///             ElevatedButton(
542
  ///               child: const Text('Second Page >'),
543 544 545 546 547 548 549 550 551 552 553 554
  ///               onPressed: () {
  ///                 Navigator.pushNamed(context, '/second_page');
  ///               },
  ///             ),
  ///           ],
  ///         ),
  ///       ),
  ///     );
  ///   }
  /// }
  ///
  /// class SecondPage extends StatefulWidget {
555 556
  ///   const SecondPage({Key? key}) : super(key: key);
  ///
557
  ///   @override
558
  ///   State<SecondPage> createState() => _SecondPageState();
559 560 561 562 563 564
  /// }
  ///
  /// class _SecondPageState extends State<SecondPage> {
  ///
  ///   bool _showRectangle = false;
  ///
565
  ///   Future<void> _navigateLocallyToShowRectangle() async {
566 567 568 569
  ///     // 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);
570
  ///     ModalRoute.of(context)?.addLocalHistoryEntry(
571
  ///         LocalHistoryEntry(
572 573 574 575 576 577 578 579 580 581
  ///             onRemove: () {
  ///               // Hide the red rectangle.
  ///               setState(() => _showRectangle = false);
  ///             }
  ///         )
  ///     );
  ///   }
  ///
  ///   @override
  ///   Widget build(BuildContext context) {
582
  ///     final Widget localNavContent = _showRectangle
583
  ///       ? Container(
584 585 586 587
  ///           width: 100.0,
  ///           height: 100.0,
  ///           color: Colors.red,
  ///         )
588
  ///       : ElevatedButton(
589
  ///           onPressed: _navigateLocallyToShowRectangle,
590
  ///           child: const Text('Show Rectangle'),
591 592
  ///         );
  ///
593
  ///     return Scaffold(
594
  ///       body: Center(
595
  ///         child: Column(
596 597 598
  ///           mainAxisAlignment: MainAxisAlignment.center,
  ///           children: <Widget>[
  ///             localNavContent,
599
  ///             ElevatedButton(
600
  ///               child: const Text('< Back'),
601 602
  ///               onPressed: () {
  ///                 // Pop a route. If this is pressed while the red rectangle is
nt4f04uNd's avatar
nt4f04uNd committed
603
  ///                 // visible then it will pop our local history entry, which
604 605 606 607 608 609 610 611 612 613 614 615
  ///                 // will hide the red rectangle. Otherwise, the SecondPage will
  ///                 // navigate back to the HomePage.
  ///                 Navigator.of(context).pop();
  ///               },
  ///             ),
  ///           ],
  ///         ),
  ///       ),
  ///     );
  ///   }
  /// }
  /// ```
616
  /// {@end-tool}
Hixie's avatar
Hixie committed
617 618 619 620
  void addLocalHistoryEntry(LocalHistoryEntry entry) {
    assert(entry._owner == null);
    entry._owner = this;
    _localHistory ??= <LocalHistoryEntry>[];
621 622
    final bool wasEmpty = _localHistory!.isEmpty;
    _localHistory!.add(entry);
623 624
    if (wasEmpty)
      changedInternalState();
Hixie's avatar
Hixie committed
625
  }
626 627 628

  /// Remove a local history entry from this route.
  ///
629 630
  /// The entry's [LocalHistoryEntry.onRemove] callback, if any, will be called
  /// synchronously.
Hixie's avatar
Hixie committed
631 632 633
  void removeLocalHistoryEntry(LocalHistoryEntry entry) {
    assert(entry != null);
    assert(entry._owner == this);
634 635
    assert(_localHistory!.contains(entry));
    _localHistory!.remove(entry);
Hixie's avatar
Hixie committed
636 637
    entry._owner = null;
    entry._notifyRemoved();
638
    if (_localHistory!.isEmpty) {
639
      if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) {
640 641 642
        // 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.
643
        SchedulerBinding.instance.addPostFrameCallback((Duration duration) {
644 645 646 647 648 649
          changedInternalState();
        });
      } else {
        changedInternalState();
      }
    }
Hixie's avatar
Hixie committed
650
  }
651

652
  @override
653 654 655
  Future<RoutePopDisposition> willPop() async {
    if (willHandlePopInternally)
      return RoutePopDisposition.pop;
656
    return super.willPop();
657 658
  }

659
  @override
660
  bool didPop(T? result) {
661 662
    if (_localHistory != null && _localHistory!.isNotEmpty) {
      final LocalHistoryEntry entry = _localHistory!.removeLast();
Hixie's avatar
Hixie committed
663 664 665
      assert(entry._owner == this);
      entry._owner = null;
      entry._notifyRemoved();
666
      if (_localHistory!.isEmpty)
667
        changedInternalState();
Hixie's avatar
Hixie committed
668 669 670 671
      return false;
    }
    return super.didPop(result);
  }
672 673

  @override
Hixie's avatar
Hixie committed
674
  bool get willHandlePopInternally {
675
    return _localHistory != null && _localHistory!.isNotEmpty;
Hixie's avatar
Hixie committed
676
  }
Hixie's avatar
Hixie committed
677 678
}

679
class _DismissModalAction extends DismissAction {
680 681 682 683 684 685
  _DismissModalAction(this.context);

  final BuildContext context;

  @override
  bool isEnabled(DismissIntent intent) {
686
    final ModalRoute<dynamic> route = ModalRoute.of<dynamic>(context)!;
687 688 689
    return route.barrierDismissible;
  }

690 691
  @override
  Object invoke(DismissIntent intent) {
692
    return Navigator.of(context).maybePop();
693 694 695
  }
}

Hixie's avatar
Hixie committed
696
class _ModalScopeStatus extends InheritedWidget {
697
  const _ModalScopeStatus({
698 699 700 701 702
    Key? key,
    required this.isCurrent,
    required this.canPop,
    required this.route,
    required Widget child,
703 704 705 706 707
  }) : assert(isCurrent != null),
       assert(canPop != null),
       assert(route != null),
       assert(child != null),
       super(key: key, child: child);
Hixie's avatar
Hixie committed
708

709
  final bool isCurrent;
710
  final bool canPop;
711
  final Route<dynamic> route;
Hixie's avatar
Hixie committed
712

713
  @override
Hixie's avatar
Hixie committed
714
  bool updateShouldNotify(_ModalScopeStatus old) {
715
    return isCurrent != old.isCurrent ||
716
           canPop != old.canPop ||
Hixie's avatar
Hixie committed
717 718 719
           route != old.route;
  }

720
  @override
721
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
722
    super.debugFillProperties(description);
723 724
    description.add(FlagProperty('isCurrent', value: isCurrent, ifTrue: 'active', ifFalse: 'inactive'));
    description.add(FlagProperty('canPop', value: canPop, ifTrue: 'can pop'));
Hixie's avatar
Hixie committed
725 726 727
  }
}

728
class _ModalScope<T> extends StatefulWidget {
729
  const _ModalScope({
730 731
    Key? key,
    required this.route,
732
  }) : super(key: key);
733

734
  final ModalRoute<T> route;
735

736
  @override
737
  _ModalScopeState<T> createState() => _ModalScopeState<T>();
738 739
}

740 741 742 743 744
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.
745
  Widget? _page;
746 747

  // This is the combination of the two animations for the route.
748
  late Listenable _listenable;
749

750 751
  /// The node this scope will use for its root [FocusScope] widget.
  final FocusScopeNode focusScopeNode = FocusScopeNode(debugLabel: '$_ModalScopeState Focus Scope');
752
  final ScrollController primaryScrollController = ScrollController();
753

754
  @override
755 756
  void initState() {
    super.initState();
757
    final List<Listenable> animations = <Listenable>[
758 759
      if (widget.route.animation != null) widget.route.animation!,
      if (widget.route.secondaryAnimation != null) widget.route.secondaryAnimation!,
760
    ];
761
    _listenable = Listenable.merge(animations);
762
    if (widget.route.isCurrent && _shouldRequestFocus) {
763
      widget.route.navigator!.focusScopeNode.setFirstFocus(focusScopeNode);
764
    }
765 766
  }

767
  @override
768
  void didUpdateWidget(_ModalScope<T> oldWidget) {
769
    super.didUpdateWidget(oldWidget);
770
    assert(widget.route == oldWidget.route);
771
    if (widget.route.isCurrent && _shouldRequestFocus) {
772
      widget.route.navigator!.focusScopeNode.setFirstFocus(focusScopeNode);
773
    }
774 775
  }

776
  @override
777 778 779
  void didChangeDependencies() {
    super.didChangeDependencies();
    _page = null;
780 781
  }

782
  void _forceRebuildPage() {
783
    setState(() {
784
      _page = null;
785 786 787
    });
  }

788 789 790 791 792 793
  @override
  void dispose() {
    focusScopeNode.dispose();
    super.dispose();
  }

794 795 796 797 798
  bool get _shouldIgnoreFocusRequest {
    return widget.route.animation?.status == AnimationStatus.reverse ||
      (widget.route.navigator?.userGestureInProgress ?? false);
  }

799 800 801 802
  bool get _shouldRequestFocus {
    return widget.route.navigator!.widget.requestFocus;
  }

803 804
  // This should be called to wrap any changes to route.isCurrent, route.canPop,
  // and route.offstage.
805
  void _routeSetState(VoidCallback fn) {
806
    if (widget.route.isCurrent && !_shouldIgnoreFocusRequest && _shouldRequestFocus) {
807
      widget.route.navigator!.focusScopeNode.setFirstFocus(focusScopeNode);
808
    }
809
    setState(fn);
810 811
  }

812
  @override
813
  Widget build(BuildContext context) {
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
    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
        child: Offstage(
          offstage: widget.route.offstage, // _routeSetState is called if this updates
          child: PageStorage(
            bucket: widget.route._storageBucket, // immutable
831 832 833 834 835 836
            child: Builder(
              builder: (BuildContext context) {
                return Actions(
                  actions: <Type, Action<Intent>>{
                    DismissIntent: _DismissModalAction(context),
                  },
837 838 839 840
                  child: PrimaryScrollController(
                    controller: primaryScrollController,
                    child: FocusScope(
                      node: focusScopeNode, // immutable
841
                      child: FocusTrap(
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
                        focusScopeNode: focusScopeNode,
                        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,
                                    );
                                  },
                                  child: child,
                                ),
                              );
                            },
                            child: _page ??= RepaintBoundary(
                              key: widget.route._subtreeKey, // immutable
                              child: Builder(
                                builder: (BuildContext context) {
                                  return widget.route.buildPage(
                                    context,
                                    widget.route.animation!,
                                    widget.route.secondaryAnimation!,
877 878 879
                                  );
                                },
                              ),
880 881 882
                            ),
                          ),
                        ),
883
                      ),
884
                    ),
885
                  ),
886 887
                );
              },
888 889 890 891
            ),
          ),
        ),
      ),
892
    );
893 894 895
  }
}

896
/// A route that blocks interaction with previous routes.
897
///
898 899 900 901 902 903
/// [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.
904
abstract class ModalRoute<T> extends TransitionRoute<T> with LocalHistoryRoute<T> {
905
  /// Creates a route that blocks interaction with previous routes.
906
  ModalRoute({
907
    RouteSettings? settings,
908 909
    this.filter,
  }) : super(settings: settings);
910 911 912 913 914

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

Hixie's avatar
Hixie committed
917 918
  // The API for general users of this class

919 920
  /// Returns the modal route most closely associated with the given context.
  ///
921
  /// Returns null if the given context is not associated with a modal route.
922
  ///
923 924
  /// {@tool snippet}
  ///
925 926 927
  /// Typical usage is as follows:
  ///
  /// ```dart
928
  /// ModalRoute<int>? route = ModalRoute.of<int>(context);
929
  /// ```
930
  /// {@end-tool}
931 932
  ///
  /// The given [BuildContext] will be rebuilt if the state of the route changes
933
  /// while it is visible (specifically, if [isCurrent] or [canPop] change value).
934
  @optionalTypeArgs
935
  static ModalRoute<T>? of<T extends Object?>(BuildContext context) {
936 937
    final _ModalScopeStatus? widget = context.dependOnInheritedWidgetOfExactType<_ModalScopeStatus>();
    return widget?.route as ModalRoute<T>?;
Hixie's avatar
Hixie committed
938 939
  }

940 941
  /// Schedule a call to [buildTransitions].
  ///
942
  /// Whenever you need to change internal state for a [ModalRoute] object, make
943
  /// the change in a function that you pass to [setState], as in:
944 945 946 947 948
  ///
  /// ```dart
  /// setState(() { myState = newValue });
  /// ```
  ///
949
  /// If you just change the state directly without calling [setState], then the
950 951 952 953 954
  /// route will not be scheduled for rebuilding, meaning that its rendering
  /// will not be updated.
  @protected
  void setState(VoidCallback fn) {
    if (_scopeKey.currentState != null) {
955
      _scopeKey.currentState!._routeSetState(fn);
956 957 958 959 960 961 962 963
    } 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
964 965 966 967 968 969
  /// 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) {
970
    return (Route<dynamic> route) {
Hans Muller's avatar
Hans Muller committed
971
      return !route.willHandlePopInternally
972 973
          && route is ModalRoute
          && route.settings.name == name;
Hans Muller's avatar
Hans Muller committed
974 975
    };
  }
976 977 978

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

979
  /// Override this method to build the primary content of this route.
980
  ///
981 982 983 984 985 986 987 988 989 990
  /// 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.
  ///
991 992 993 994 995 996 997 998
  /// 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.
999 1000 1001 1002 1003
  ///
  /// 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.
1004
  Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation);
1005

1006 1007
  /// Override this method to wrap the [child] with one or more transition
  /// widgets that define how the route arrives on and leaves the screen.
1008
  ///
1009 1010 1011 1012
  /// 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
1013 1014
  /// time the [Route]'s state changes while it is visible (e.g. if the value of
  /// [canPop] changes on the active route).
1015
  ///
1016
  /// The [buildTransitions] method is typically used to define transitions
1017 1018 1019 1020 1021 1022
  /// 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.
  ///
1023
  /// {@tool snippet}
1024 1025 1026 1027 1028 1029
  /// 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.
  ///
1030 1031 1032 1033
  /// 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.
  ///
1034
  /// ```dart
1035
  /// PageRouteBuilder(
1036 1037 1038 1039
  ///   pageBuilder: (BuildContext context,
  ///       Animation<double> animation,
  ///       Animation<double> secondaryAnimation,
  ///   ) {
1040
  ///     return Scaffold(
1041 1042
  ///       appBar: AppBar(title: const Text('Hello')),
  ///       body: const Center(
1043
  ///         child: Text('Hello World'),
1044 1045 1046 1047 1048 1049 1050 1051 1052
  ///       ),
  ///     );
  ///   },
  ///   transitionsBuilder: (
  ///       BuildContext context,
  ///       Animation<double> animation,
  ///       Animation<double> secondaryAnimation,
  ///       Widget child,
  ///    ) {
1053 1054
  ///     return SlideTransition(
  ///       position: Tween<Offset>(
1055 1056
  ///         begin: const Offset(0.0, 1.0),
  ///         end: Offset.zero,
1057 1058 1059 1060
  ///       ).animate(animation),
  ///       child: child, // child is the value returned by pageBuilder
  ///     );
  ///   },
1061
  /// )
1062
  /// ```
1063
  /// {@end-tool}
1064
  ///
1065
  /// When the [Navigator] pushes a route on the top of its stack, the
1066 1067 1068 1069 1070
  /// [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
1071
  /// runs from 0.0 to 1.0. When the Navigator pops the topmost route, the
1072 1073
  /// secondaryAnimation for the route below it runs from 1.0 to 0.0.
  ///
1074
  /// {@tool snippet}
1075
  /// The example below adds a transition that's driven by the
1076
  /// [secondaryAnimation]. When this route disappears because a new route has
1077 1078 1079 1080 1081
  /// 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
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
  /// PageRouteBuilder(
  ///   pageBuilder: (BuildContext context,
  ///       Animation<double> animation,
  ///       Animation<double> secondaryAnimation,
  ///   ) {
  ///     return Scaffold(
  ///       appBar: AppBar(title: const Text('Hello')),
  ///       body: const Center(
  ///         child: Text('Hello World'),
  ///       ),
  ///     );
  ///   },
1094 1095 1096 1097 1098 1099
  ///   transitionsBuilder: (
  ///       BuildContext context,
  ///       Animation<double> animation,
  ///       Animation<double> secondaryAnimation,
  ///       Widget child,
  ///   ) {
1100
  ///     return SlideTransition(
1101
  ///       position: Tween<Offset>(
1102 1103
  ///         begin: const Offset(0.0, 1.0),
  ///         end: Offset.zero,
1104
  ///       ).animate(animation),
1105
  ///       child: SlideTransition(
1106
  ///         position: Tween<Offset>(
1107 1108
  ///           begin: Offset.zero,
  ///           end: const Offset(0.0, 1.0),
1109 1110 1111
  ///         ).animate(secondaryAnimation),
  ///         child: child,
  ///       ),
1112 1113 1114
  ///      );
  ///   },
  /// )
1115
  /// ```
1116
  /// {@end-tool}
1117 1118
  ///
  /// In practice the `secondaryAnimation` is used pretty rarely.
1119
  ///
1120
  /// The arguments to this method are as follows:
1121
  ///
1122 1123 1124
  ///  * `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]
1125
  ///    pops the topmost route this animation runs from 1.0 to 0.0.
1126 1127
  ///  * [secondaryAnimation]: When the Navigator pushes a new route
  ///    on the top of its stack, the old topmost route's [secondaryAnimation]
1128
  ///    runs from 0.0 to 1.0. When the [Navigator] pops the topmost route, the
1129
  ///    [secondaryAnimation] for the route below it runs from 1.0 to 0.0.
1130
  ///  * `child`, the page contents, as returned by [buildPage].
1131 1132 1133 1134 1135
  ///
  /// 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.
1136
  Widget buildTransitions(
1137 1138 1139 1140
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
    Widget child,
1141
  ) {
1142 1143 1144
    return child;
  }

1145
  @override
1146 1147
  void install() {
    super.install();
1148 1149
    _animationProxy = ProxyAnimation(super.animation);
    _secondaryAnimationProxy = ProxyAnimation(super.secondaryAnimation);
1150 1151
  }

1152
  @override
1153
  TickerFuture didPush() {
1154
    if (_scopeKey.currentState != null && navigator!.widget.requestFocus) {
1155
      navigator!.focusScopeNode.setFirstFocus(_scopeKey.currentState!.focusScopeNode);
1156
    }
1157
    return super.didPush();
1158 1159
  }

1160 1161
  @override
  void didAdd() {
1162
    if (_scopeKey.currentState != null && navigator!.widget.requestFocus) {
1163
      navigator!.focusScopeNode.setFirstFocus(_scopeKey.currentState!.focusScopeNode);
1164 1165 1166 1167
    }
    super.didAdd();
  }

1168 1169
  // The API for subclasses to override - used by this class

1170
  /// {@template flutter.widgets.ModalRoute.barrierDismissible}
Hixie's avatar
Hixie committed
1171
  /// Whether you can dismiss this route by tapping the modal barrier.
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
  ///
  /// 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.
  ///
  /// If [barrierDismissible] is true, then tapping this barrier will cause the
  /// current route to be popped (see [Navigator.pop]) with null as the value.
  ///
  /// If [barrierDismissible] is false, then tapping the barrier has no effect.
  ///
1185 1186 1187 1188 1189 1190 1191 1192
  /// 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.
1193
  ///
1194 1195 1196 1197
  /// See also:
  ///
  ///  * [barrierColor], which controls the color of the scrim for this route.
  ///  * [ModalBarrier], the widget that implements this feature.
1198
  /// {@endtemplate}
1199
  bool get barrierDismissible;
1200

1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
  /// 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
1212
  /// excluded from the semantics tree and tapping on the modal barrier
1213
  /// has no effect.
1214 1215 1216 1217 1218 1219 1220 1221 1222
  ///
  /// 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.
1223 1224
  bool get semanticsDismissible => true;

1225
  /// {@template flutter.widgets.ModalRoute.barrierColor}
Hixie's avatar
Hixie committed
1226 1227
  /// The color to use for the modal barrier. If this is null, the barrier will
  /// be transparent.
1228
  ///
1229 1230 1231 1232 1233 1234 1235
  /// 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.
  ///
1236 1237
  /// The color is ignored, and the barrier made invisible, when
  /// [ModalRoute.offstage] is true.
1238 1239 1240
  ///
  /// While the route is animating into position, the color is animated from
  /// transparent to the specified color.
1241
  /// {@endtemplate}
1242
  ///
1243 1244 1245 1246 1247 1248 1249 1250
  /// 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.
1251
  ///
1252 1253
  /// {@tool snippet}
  ///
1254 1255
  /// For example, to make the barrier color use the theme's
  /// background color, one could say:
1256 1257 1258 1259 1260 1261 1262
  ///
  /// ```dart
  /// Color get barrierColor => Theme.of(navigator.context).backgroundColor;
  /// ```
  ///
  /// {@end-tool}
  ///
1263 1264 1265 1266 1267
  /// See also:
  ///
  ///  * [barrierDismissible], which controls the behavior of the barrier when
  ///    tapped.
  ///  * [ModalBarrier], the widget that implements this feature.
1268
  Color? get barrierColor;
1269

1270
  /// {@template flutter.widgets.ModalRoute.barrierLabel}
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
  /// 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.
1282
  /// {@endtemplate}
1283
  ///
1284 1285 1286 1287 1288 1289 1290 1291
  /// 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.
1292
  ///
1293 1294 1295 1296 1297
  /// See also:
  ///
  ///  * [barrierDismissible], which controls the behavior of the barrier when
  ///    tapped.
  ///  * [ModalBarrier], the widget that implements this feature.
1298
  String? get barrierLabel;
1299

1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
  /// 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].
  ///
1312 1313 1314 1315 1316 1317 1318 1319
  /// 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.
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
  ///
  /// 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;

1331
  /// {@template flutter.widgets.ModalRoute.maintainState}
1332 1333 1334 1335 1336 1337 1338
  /// 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.
1339
  /// {@endtemplate}
1340
  ///
1341 1342 1343
  /// If this getter would ever start returning a different value, the
  /// [changedInternalState] should be invoked so that the change can take
  /// effect.
1344 1345
  bool get maintainState;

1346 1347 1348

  // The API for _ModalScope and HeroController

1349 1350 1351 1352 1353 1354 1355
  /// 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.
1356 1357 1358
  ///
  /// The modal barrier, if any, is not rendered if [offstage] is true (see
  /// [barrierColor]).
1359 1360
  ///
  /// Whenever this changes value, [changedInternalState] is called.
1361 1362
  bool get offstage => _offstage;
  bool _offstage = false;
1363
  set offstage(bool value) {
1364 1365
    if (_offstage == value)
      return;
1366 1367 1368
    setState(() {
      _offstage = value;
    });
1369 1370
    _animationProxy!.parent = _offstage ? kAlwaysCompleteAnimation : super.animation;
    _secondaryAnimationProxy!.parent = _offstage ? kAlwaysDismissedAnimation : super.secondaryAnimation;
1371
    changedInternalState();
1372 1373
  }

1374
  /// The build context for the subtree containing the primary content of this route.
1375
  BuildContext? get subtreeContext => _subtreeKey.currentContext;
1376

1377
  @override
1378 1379
  Animation<double>? get animation => _animationProxy;
  ProxyAnimation? _animationProxy;
1380 1381

  @override
1382 1383
  Animation<double>? get secondaryAnimation => _secondaryAnimationProxy;
  ProxyAnimation? _secondaryAnimationProxy;
1384

1385 1386
  final List<WillPopCallback> _willPopCallbacks = <WillPopCallback>[];

1387 1388 1389 1390 1391
  /// 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.
1392 1393 1394 1395 1396 1397 1398 1399
  ///
  /// 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
  /// for ModalRoute descendants to collectively define the value of `willPop`.
  ///
  /// See also:
  ///
1400 1401 1402 1403 1404
  ///  * [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.
1405
  @override
1406
  Future<RoutePopDisposition> willPop() async {
1407
    final _ModalScopeState<T>? scope = _scopeKey.currentState;
1408
    assert(scope != null);
1409
    for (final WillPopCallback callback in List<WillPopCallback>.of(_willPopCallbacks)) {
1410
      if (await callback() != true)
1411
        return RoutePopDisposition.doNotPop;
1412
    }
1413
    return super.willPop();
1414 1415 1416 1417
  }

  /// Enables this route to veto attempts by the user to dismiss it.
  ///
1418
  /// {@tool snippet}
1419 1420 1421 1422 1423 1424
  /// This callback is typically added using a [WillPopScope] widget. That
  /// widget finds the enclosing [ModalRoute] and uses this function to register
  /// this callback:
  ///
  /// ```dart
  /// Widget build(BuildContext context) {
1425
  ///   return WillPopScope(
1426 1427 1428 1429 1430
  ///     onWillPop: () async {
  ///       // ask the user if they are sure
  ///       return true;
  ///     },
  ///     child: Container(),
1431 1432 1433
  ///   );
  /// }
  /// ```
1434
  /// {@end-tool}
1435 1436
  ///
  /// This callback runs asynchronously and it's possible that it will be called
1437
  /// after its route has been disposed. The callback should check [State.mounted]
1438 1439 1440 1441 1442 1443
  /// 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.
  ///
1444
  /// {@tool snippet}
1445
  /// To register a callback manually, look up the enclosing [ModalRoute] in a
1446
  /// [State.didChangeDependencies] callback:
1447 1448
  ///
  /// ```dart
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
  /// abstract class _MyWidgetState extends State<MyWidget> {
  ///   ModalRoute<dynamic>? _route;
  ///
  ///   // ...
  ///
  ///   @override
  ///   void didChangeDependencies() {
  ///    super.didChangeDependencies();
  ///    _route?.removeScopedWillPopCallback(askTheUserIfTheyAreSure);
  ///    _route = ModalRoute.of(context);
  ///    _route?.addScopedWillPopCallback(askTheUserIfTheyAreSure);
  ///   }
1461 1462
  /// }
  /// ```
1463
  /// {@end-tool}
1464
  ///
1465
  /// {@tool snippet}
1466 1467 1468 1469
  /// If you register a callback manually, be sure to remove the callback with
  /// [removeScopedWillPopCallback] by the time the widget has been disposed. A
  /// stateful widget can do this in its dispose method (continuing the previous
  /// example):
1470 1471
  ///
  /// ```dart
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
  /// abstract class _MyWidgetState2 extends State<MyWidget> {
  ///   ModalRoute<dynamic>? _route;
  ///
  ///   // ...
  ///
  ///   @override
  ///   void dispose() {
  ///     _route?.removeScopedWillPopCallback(askTheUserIfTheyAreSure);
  ///     _route = null;
  ///     super.dispose();
  ///   }
1483 1484
  /// }
  /// ```
1485
  /// {@end-tool}
1486
  ///
1487 1488
  /// See also:
  ///
1489 1490 1491 1492 1493 1494
  ///  * [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.
1495
  void addScopedWillPopCallback(WillPopCallback callback) {
1496 1497
    assert(_scopeKey.currentState != null, 'Tried to add a willPop callback to a route that is not currently in the tree.');
    _willPopCallbacks.add(callback);
1498 1499 1500 1501 1502 1503
  }

  /// Remove one of the callbacks run by [willPop].
  ///
  /// See also:
  ///
1504 1505 1506
  ///  * [Form], which provides an `onWillPop` callback that uses this mechanism.
  ///  * [addScopedWillPopCallback], which adds callback to the list
  ///    checked by [willPop].
1507
  void removeScopedWillPopCallback(WillPopCallback callback) {
1508 1509
    assert(_scopeKey.currentState != null, 'Tried to remove a willPop callback from a route that is not currently in the tree.');
    _willPopCallbacks.remove(callback);
1510 1511
  }

1512 1513
  /// True if one or more [WillPopCallback] callbacks exist.
  ///
1514 1515 1516 1517
  /// 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.
1518
  ///
1519 1520 1521 1522
  /// 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.
  ///
1523 1524
  /// See also:
  ///
1525 1526 1527 1528
  ///  * [addScopedWillPopCallback], which adds a callback.
  ///  * [removeScopedWillPopCallback], which removes a callback.
  ///  * [willHandlePopInternally], which reports on another reason why
  ///    a pop might be vetoed.
1529
  @protected
1530
  bool get hasScopedWillPopCallback {
1531 1532 1533 1534
    return _willPopCallbacks.isNotEmpty;
  }

  @override
1535
  void didChangePrevious(Route<dynamic>? previousRoute) {
1536 1537
    super.didChangePrevious(previousRoute);
    changedInternalState();
1538
  }
1539

1540 1541 1542 1543
  @override
  void changedInternalState() {
    super.changedInternalState();
    setState(() { /* internal state already changed */ });
1544
    _modalBarrier.markNeedsBuild();
1545
    _modalScope.maintainState = maintainState;
1546 1547 1548
  }

  @override
1549 1550
  void changedExternalState() {
    super.changedExternalState();
1551
    _modalBarrier.markNeedsBuild();
1552
    if (_scopeKey.currentState != null)
1553
      _scopeKey.currentState!._forceRebuildPage();
1554 1555 1556 1557
  }

  /// Whether this route can be popped.
  ///
1558 1559 1560
  /// A route can be popped if there is at least one active route below it, or
  /// if [willHandlePopInternally] returns true.
  ///
1561 1562 1563
  /// When this changes, if the route is visible, the route will
  /// rebuild, and any widgets that used [ModalRoute.of] will be
  /// notified.
1564
  bool get canPop => hasActiveRouteBelow || willHandlePopInternally;
1565

1566 1567
  // Internals

1568 1569 1570
  final GlobalKey<_ModalScopeState<T>> _scopeKey = GlobalKey<_ModalScopeState<T>>();
  final GlobalKey _subtreeKey = GlobalKey();
  final PageStorageBucket _storageBucket = PageStorageBucket();
1571

1572
  // one of the builders
1573
  late OverlayEntry _modalBarrier;
1574
  Widget _buildModalBarrier(BuildContext context) {
1575
    Widget barrier;
1576
    if (barrierColor != null && barrierColor!.alpha != 0 && !offstage) { // changedInternalState is called if barrierColor or offstage updates
1577
      assert(barrierColor != barrierColor!.withOpacity(0.0));
1578
      final Animation<Color?> color = animation!.drive(
1579
        ColorTween(
1580
          begin: barrierColor!.withOpacity(0.0),
1581 1582
          end: barrierColor, // changedInternalState is called if barrierColor updates
        ).chain(CurveTween(curve: barrierCurve)), // changedInternalState is called if barrierCurve updates
1583
      );
1584
      barrier = AnimatedModalBarrier(
1585
        color: color,
1586 1587
        dismissible: barrierDismissible, // changedInternalState is called if barrierDismissible updates
        semanticsLabel: barrierLabel, // changedInternalState is called if barrierLabel updates
1588
        barrierSemanticsDismissible: semanticsDismissible,
Hixie's avatar
Hixie committed
1589 1590
      );
    } else {
1591
      barrier = ModalBarrier(
1592 1593
        dismissible: barrierDismissible, // changedInternalState is called if barrierDismissible updates
        semanticsLabel: barrierLabel, // changedInternalState is called if barrierLabel updates
1594
        barrierSemanticsDismissible: semanticsDismissible,
1595
      );
Hixie's avatar
Hixie committed
1596
    }
1597
    if (filter != null) {
1598
      barrier = BackdropFilter(
1599
        filter: filter!,
1600 1601 1602
        child: barrier,
      );
    }
1603
    barrier = IgnorePointer(
1604 1605
      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
1606
      child: barrier,
1607
    );
1608 1609 1610 1611 1612 1613 1614 1615
    if (semanticsDismissible && barrierDismissible) {
      // To be sorted after the _modalScope.
      barrier = Semantics(
        sortKey: const OrdinalSortKey(1.0),
        child: barrier,
      );
    }
    return barrier;
1616 1617
  }

1618 1619
  // 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.
1620
  Widget? _modalScopeCache;
1621

1622
  // one of the builders
1623
  Widget _buildModalScope(BuildContext context) {
1624 1625 1626 1627 1628 1629 1630
    // 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
1631
      ),
1632 1633 1634
    );
  }

1635
  late OverlayEntry _modalScope;
1636

1637
  @override
1638 1639 1640 1641 1642
  Iterable<OverlayEntry> createOverlayEntries() {
    return <OverlayEntry>[
      _modalBarrier = OverlayEntry(builder: _buildModalBarrier),
      _modalScope = OverlayEntry(builder: _buildModalScope, maintainState: maintainState),
    ];
1643
  }
1644

1645
  @override
1646
  String toString() => '${objectRuntimeType(this, 'ModalRoute')}($settings, animation: $_animation)';
1647
}
Hixie's avatar
Hixie committed
1648 1649 1650

/// A modal route that overlays a widget over the current route.
abstract class PopupRoute<T> extends ModalRoute<T> {
1651 1652
  /// Initializes the [PopupRoute].
  PopupRoute({
1653 1654
    RouteSettings? settings,
    ui.ImageFilter? filter,
1655 1656 1657 1658
  }) : super(
         filter: filter,
         settings: settings,
       );
1659

1660
  @override
Hixie's avatar
Hixie committed
1661
  bool get opaque => false;
1662

1663 1664
  @override
  bool get maintainState => true;
Hixie's avatar
Hixie committed
1665
}
1666 1667 1668 1669

/// A [Navigator] observer that notifies [RouteAware]s of changes to the
/// state of their [Route].
///
1670 1671 1672
/// [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>`
1673 1674 1675
/// will inform subscribed [RouteAware]s whenever the user navigates away from
/// the current page route to another page route.
///
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
/// To be informed about route changes of any type, consider instantiating a
/// `RouteObserver<Route>`.
///
/// ## Type arguments
///
/// When using more aggressive
/// [lints](http://dart-lang.github.io/linter/lints/), in particular lints such
/// as `always_specify_types`, the Dart analyzer will require that certain types
/// be given with their type arguments. Since the [Route] class and its
/// subclasses have a type argument, this includes the arguments passed to this
1686
/// class. Consider using `dynamic` to specify the entire class of routes rather
1687
/// than only specific subtypes. For example, to watch for all [ModalRoute]
1688
/// variants, the `RouteObserver<ModalRoute<dynamic>>` type may be used.
1689
///
1690
/// {@tool snippet}
1691
///
1692
/// To make a [StatefulWidget] aware of its current [Route] state, implement
1693
/// [RouteAware] in its [State] and subscribe it to a [RouteObserver]:
1694 1695
///
/// ```dart
1696
/// // Register the RouteObserver as a navigation observer.
1697
/// final RouteObserver<ModalRoute<void>> routeObserver = RouteObserver<ModalRoute<void>>();
1698
/// void main() {
1699 1700
///   runApp(MaterialApp(
///     home: Container(),
1701
///     navigatorObservers: <RouteObserver<ModalRoute<void>>>[ routeObserver ],
1702 1703 1704 1705
///   ));
/// }
///
/// class RouteAwareWidget extends StatefulWidget {
1706 1707 1708
///   const RouteAwareWidget({Key? key}) : super(key: key);
///
///   @override
1709
///   State<RouteAwareWidget> createState() => RouteAwareWidgetState();
1710 1711 1712
/// }
///
/// // Implement RouteAware in a widget's state and subscribe it to the RouteObserver.
1713
/// class RouteAwareWidgetState extends State<RouteAwareWidget> with RouteAware {
1714
///
1715 1716 1717
///   @override
///   void didChangeDependencies() {
///     super.didChangeDependencies();
1718
///     routeObserver.subscribe(this, ModalRoute.of(context)!);
1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
///   }
///
///   @override
///   void dispose() {
///     routeObserver.unsubscribe(this);
///     super.dispose();
///   }
///
///   @override
///   void didPush() {
1729
///     // Route was pushed onto navigator and is now topmost route.
1730 1731 1732 1733
///   }
///
///   @override
///   void didPopNext() {
1734
///     // Covering route was popped off the navigator.
1735 1736
///   }
///
1737
///   @override
1738
///   Widget build(BuildContext context) => Container();
1739
///
1740 1741
/// }
/// ```
1742
/// {@end-tool}
1743
class RouteObserver<R extends Route<dynamic>> extends NavigatorObserver {
1744
  final Map<R, Set<RouteAware>> _listeners = <R, Set<RouteAware>>{};
1745

1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
  /// 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;
  }

1759 1760 1761 1762 1763
  /// 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.
1764
  void subscribe(RouteAware routeAware, R route) {
1765 1766
    assert(routeAware != null);
    assert(route != null);
1767
    final Set<RouteAware> subscribers = _listeners.putIfAbsent(route, () => <RouteAware>{});
1768
    if (subscribers.add(routeAware)) {
1769 1770 1771 1772
      routeAware.didPush();
    }
  }

1773 1774
  /// Unsubscribe [routeAware].
  ///
1775 1776
  /// [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.
1777 1778
  void unsubscribe(RouteAware routeAware) {
    assert(routeAware != null);
1779 1780
    final List<R> routes = _listeners.keys.toList();
    for (final R route in routes) {
1781
      final Set<RouteAware>? subscribers = _listeners[route];
1782 1783 1784 1785 1786 1787
      if (subscribers != null) {
        subscribers.remove(routeAware);
        if (subscribers.isEmpty) {
          _listeners.remove(route);
        }
      }
1788
    }
1789 1790 1791
  }

  @override
1792
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
1793
    if (route is R && previousRoute is R) {
1794
      final List<RouteAware>? previousSubscribers = _listeners[previousRoute]?.toList();
1795 1796

      if (previousSubscribers != null) {
1797
        for (final RouteAware routeAware in previousSubscribers) {
1798 1799 1800 1801
          routeAware.didPopNext();
        }
      }

1802
      final List<RouteAware>? subscribers = _listeners[route]?.toList();
1803 1804

      if (subscribers != null) {
1805
        for (final RouteAware routeAware in subscribers) {
1806 1807 1808
          routeAware.didPop();
        }
      }
1809 1810 1811 1812
    }
  }

  @override
1813
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
1814
    if (route is R && previousRoute is R) {
1815
      final Set<RouteAware>? previousSubscribers = _listeners[previousRoute];
1816 1817

      if (previousSubscribers != null) {
1818
        for (final RouteAware routeAware in previousSubscribers) {
1819 1820 1821
          routeAware.didPushNext();
        }
      }
1822 1823 1824 1825
    }
  }
}

1826 1827 1828 1829
/// 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.
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
abstract class RouteAware {
  /// 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() { }
1844
}
1845

1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867
/// 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.
///
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882
/// {@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}
///
1883 1884
/// See also:
///
1885 1886
///  * [DisplayFeatureSubScreen], which documents the specifics of how
///    [DisplayFeature]s can split the screen into sub-screens.
1887 1888 1889 1890 1891 1892
///  * [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({
1893
    required RoutePageBuilder pageBuilder,
1894
    bool barrierDismissible = true,
1895
    Color? barrierColor = const Color(0x80000000),
1896
    String? barrierLabel,
1897
    Duration transitionDuration = const Duration(milliseconds: 200),
1898 1899
    RouteTransitionsBuilder? transitionBuilder,
    RouteSettings? settings,
1900
    this.anchorPoint,
1901 1902 1903 1904 1905 1906 1907 1908
  }) : assert(barrierDismissible != null),
       _pageBuilder = pageBuilder,
       _barrierDismissible = barrierDismissible,
       _barrierLabel = barrierLabel,
       _barrierColor = barrierColor,
       _transitionDuration = transitionDuration,
       _transitionBuilder = transitionBuilder,
       super(settings: settings);
1909 1910 1911 1912 1913 1914 1915 1916

  final RoutePageBuilder _pageBuilder;

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

  @override
1917 1918
  String? get barrierLabel => _barrierLabel;
  final String? _barrierLabel;
1919 1920

  @override
1921 1922
  Color? get barrierColor => _barrierColor;
  final Color? _barrierColor;
1923 1924 1925 1926 1927

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

1928
  final RouteTransitionsBuilder? _transitionBuilder;
1929

1930 1931 1932
  /// {@macro flutter.widgets.DisplayFeatureSubScreen.anchorPoint}
  final Offset? anchorPoint;

1933 1934
  @override
  Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
1935
    return Semantics(
1936 1937
      scopesRoute: true,
      explicitChildNodes: true,
1938 1939 1940 1941
      child: DisplayFeatureSubScreen(
        anchorPoint: anchorPoint,
        child: _pageBuilder(context, animation, secondaryAnimation),
      ),
1942 1943 1944 1945 1946 1947
    );
  }

  @override
  Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
    if (_transitionBuilder == null) {
1948
      return FadeTransition(
1949 1950 1951 1952 1953 1954
        opacity: CurvedAnimation(
          parent: animation,
          curve: Curves.linear,
        ),
        child: child,
      );
1955
    } // Some default transition
1956
    return _transitionBuilder!(context, animation, secondaryAnimation, child);
1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971
  }
}

/// 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`
/// does not share a context with the location that `showGeneralDialog` is
/// originally called from. Use a [StatefulBuilder] or a custom
/// [StatefulWidget] if the dialog needs to update dynamically. The
/// `pageBuilder` argument can not be null.
///
1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983
/// 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)`.
1984 1985 1986
///
/// The `barrierDismissible` argument is used to determine whether this route
/// can be dismissed by tapping the modal barrier. This argument defaults
1987
/// to false. If `barrierDismissible` is true, a non-null `barrierLabel` must be
1988 1989 1990
/// provided.
///
/// The `barrierLabel` argument is the semantic label used for a dismissible
1991
/// barrier. This argument defaults to `null`.
1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
///
/// 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.
///
2004 2005 2006
/// The `routeSettings` will be used in the construction of the dialog's route.
/// See [RouteSettings] for more details.
///
2007 2008
/// {@macro flutter.widgets.RawDialogRoute}
///
2009 2010 2011
/// Returns a [Future] that resolves to the value (if any) that was passed to
/// [Navigator.pop] when the dialog was closed.
///
2012 2013 2014 2015 2016 2017 2018 2019
/// ### 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].
///
2020
/// {@tool sample}
2021 2022 2023 2024 2025 2026 2027
/// 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}
///
2028
/// ** See code in examples/api/lib/widgets/routes/show_general_dialog.0.dart **
2029 2030
/// {@end-tool}
///
2031
/// See also:
2032
///
2033 2034
///  * [DisplayFeatureSubScreen], which documents the specifics of how
///    [DisplayFeature]s can split the screen into sub-screens.
2035 2036
///  * [showDialog], which displays a Material-style dialog.
///  * [showCupertinoDialog], which displays an iOS-style dialog.
2037
Future<T?> showGeneralDialog<T extends Object?>({
2038 2039
  required BuildContext context,
  required RoutePageBuilder pageBuilder,
2040
  bool barrierDismissible = false,
2041
  String? barrierLabel,
2042 2043
  Color barrierColor = const Color(0x80000000),
  Duration transitionDuration = const Duration(milliseconds: 200),
2044
  RouteTransitionsBuilder? transitionBuilder,
2045
  bool useRootNavigator = true,
2046
  RouteSettings? routeSettings,
2047
  Offset? anchorPoint,
2048 2049
}) {
  assert(pageBuilder != null);
2050
  assert(useRootNavigator != null);
2051
  assert(!barrierDismissible || barrierLabel != null);
2052
  return Navigator.of(context, rootNavigator: useRootNavigator).push<T>(RawDialogRoute<T>(
2053 2054 2055 2056 2057 2058
    pageBuilder: pageBuilder,
    barrierDismissible: barrierDismissible,
    barrierLabel: barrierLabel,
    barrierColor: barrierColor,
    transitionDuration: transitionDuration,
    transitionBuilder: transitionBuilder,
2059
    settings: routeSettings,
2060
    anchorPoint: anchorPoint,
2061 2062 2063 2064 2065 2066 2067
  ));
}

/// 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.
2068
typedef RoutePageBuilder = Widget Function(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation);
2069 2070 2071 2072 2073

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

2076 2077 2078
/// The [FocusTrap] widget removes focus when a mouse primary pointer makes contact with another
/// region of the screen.
///
2079 2080 2081 2082
/// When a primary pointer makes contact with the screen, this widget determines if that pointer
/// contacted an existing focused widget. If not, this asks the [FocusScopeNode] to reset the
/// focus state. This allows [TextField]s and other focusable widgets to give up their focus
/// state, without creating a gesture detector that competes with others on screen.
2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095
///
/// In cases where focus is conceptually larger than the focused render object, a [FocusTrapArea]
/// can be used to expand the focus area to include all render objects below that. This is used by
/// the [TextField] widgets to prevent a loss of focus when interacting with decorations on the
/// text area.
///
/// See also:
///
///  * [FocusTrapArea], the widget that allows expanding the conceptual focus area.
class FocusTrap extends SingleChildRenderObjectWidget {

  /// Create a new [FocusTrap] widget scoped to the provided [focusScopeNode].
  const FocusTrap({
2096 2097
    required this.focusScopeNode,
    required Widget child,
2098 2099
    Key? key,
  }) : super(child: child, key: key);
2100

2101
  /// The [focusScopeNode] that this focus trap widget operates on.
2102 2103 2104 2105 2106 2107 2108 2109
  final FocusScopeNode focusScopeNode;

  @override
  RenderObject createRenderObject(BuildContext context) {
    return _RenderFocusTrap(focusScopeNode);
  }

  @override
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144
  void updateRenderObject(BuildContext context, RenderObject renderObject) {
    if (renderObject is _RenderFocusTrap)
      renderObject.focusScopeNode = focusScopeNode;
  }
}

/// Declares a widget subtree which is part of the provided [focusNode]'s focus area
/// without attaching focus to that region.
///
/// This is used by text field widgets which decorate a smaller editable text area.
/// This area is conceptually part of the editable text, but not attached to the
/// focus context. The [FocusTrapArea] is used to inform the framework of this
/// relationship, so that primary pointer contact inside of this region but above
/// the editable text focus will not trigger loss of focus.
///
/// See also:
///
///  * [FocusTrap], the widget which removes focus based on primary pointer interactions.
class FocusTrapArea extends SingleChildRenderObjectWidget {

  /// Create a new [FocusTrapArea] that expands the area of the provided [focusNode].
  const FocusTrapArea({required this.focusNode, Key? key, Widget? child}) : super(key: key, child: child);

  /// The [FocusNode] that the focus trap area will expand to.
  final FocusNode focusNode;

  @override
  RenderObject createRenderObject(BuildContext context) {
    return _RenderFocusTrapArea(focusNode);
  }

  @override
  void updateRenderObject(BuildContext context, RenderObject renderObject) {
    if (renderObject is _RenderFocusTrapArea)
      renderObject.focusNode = focusNode;
2145 2146 2147
  }
}

2148 2149 2150 2151 2152 2153
class _RenderFocusTrapArea extends RenderProxyBox {
  _RenderFocusTrapArea(this.focusNode);

  FocusNode focusNode;
}

2154
class _RenderFocusTrap extends RenderProxyBoxWithHitTestBehavior {
2155
  _RenderFocusTrap(this._focusScopeNode);
2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203

  Rect? currentFocusRect;
  Expando<BoxHitTestResult> cachedResults = Expando<BoxHitTestResult>();

  FocusScopeNode _focusScopeNode;
  FocusScopeNode get focusScopeNode => _focusScopeNode;
  set focusScopeNode(FocusScopeNode value) {
    if (focusScopeNode == value)
      return;
    _focusScopeNode = value;
  }

  @override
  bool hitTest(BoxHitTestResult result, { required Offset position }) {
    bool hitTarget = false;
    if (size.contains(position)) {
      hitTarget = hitTestChildren(result, position: position) || hitTestSelf(position);
      if (hitTarget) {
        final BoxHitTestEntry entry = BoxHitTestEntry(this, position);
        cachedResults[entry] = result;
        result.add(entry);
      }
    }
    return hitTarget;
  }

  /// The focus dropping behavior is only present on desktop platforms
  /// and mobile browsers.
  bool get _shouldIgnoreEvents {
    switch (defaultTargetPlatform) {
      case TargetPlatform.android:
      case TargetPlatform.iOS:
        return !kIsWeb;
      case TargetPlatform.linux:
      case TargetPlatform.macOS:
      case TargetPlatform.windows:
      case TargetPlatform.fuchsia:
        return false;
    }
  }

  @override
  void handleEvent(PointerEvent event, HitTestEntry entry) {
    assert(debugHandleEvent(event, entry));
    if (event is! PointerDownEvent
      || event.buttons != kPrimaryButton
      || event.kind != PointerDeviceKind.mouse
      || _shouldIgnoreEvents
2204
      || _focusScopeNode.focusedChild == null) {
2205 2206 2207
      return;
    }
    final BoxHitTestResult? result = cachedResults[entry];
2208
    final FocusNode? focusNode = _focusScopeNode.focusedChild;
2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222
    if (focusNode == null || result == null)
      return;

    final RenderObject? renderObject = focusNode.context?.findRenderObject();
    if (renderObject == null)
      return;

    bool hitCurrentFocus = false;
    for (final HitTestEntry entry in result.path) {
      final HitTestTarget target = entry.target;
      if (target == renderObject) {
        hitCurrentFocus = true;
        break;
      }
2223 2224 2225 2226
      if (target is _RenderFocusTrapArea && target.focusNode == focusNode) {
        hitCurrentFocus = true;
        break;
      }
2227 2228
    }
    if (!hitCurrentFocus)
2229
      focusNode.unfocus();
2230 2231
  }
}