-
Notifications
You must be signed in to change notification settings - Fork 26.8k
/
routes.dart
2439 lines (2252 loc) · 91.1 KB
/
routes.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
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
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:math';
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'actions.dart';
import 'basic.dart';
import 'display_feature_sub_screen.dart';
import 'focus_manager.dart';
import 'focus_scope.dart';
import 'focus_traversal.dart';
import 'framework.dart';
import 'modal_barrier.dart';
import 'navigator.dart';
import 'overlay.dart';
import 'page_storage.dart';
import 'primary_scroll_controller.dart';
import 'restoration.dart';
import 'scroll_controller.dart';
import 'transitions.dart';
// Examples can assume:
// late NavigatorState navigator;
// late BuildContext context;
// Future<bool> askTheUserIfTheyAreSure() async { return true; }
// abstract class MyWidget extends StatefulWidget { const MyWidget({super.key}); }
// late dynamic _myState, newValue;
// late StateSetter setState;
/// A route that displays widgets in the [Navigator]'s [Overlay].
///
/// See also:
///
/// * [Route], which documents the meaning of the `T` generic type argument.
abstract class OverlayRoute<T> extends Route<T> {
/// Creates a route that knows how to interact with an [Overlay].
OverlayRoute({
super.settings,
});
/// Subclasses should override this getter to return the builders for the overlay.
@factory
Iterable<OverlayEntry> createOverlayEntries();
@override
List<OverlayEntry> get overlayEntries => _overlayEntries;
final List<OverlayEntry> _overlayEntries = <OverlayEntry>[];
@override
void install() {
assert(_overlayEntries.isEmpty);
_overlayEntries.addAll(createOverlayEntries());
super.install();
}
/// Controls whether [didPop] calls [NavigatorState.finalizeRoute].
///
/// If true, this route removes its overlay entries during [didPop].
/// Subclasses can override this getter if they want to delay finalization
/// (for example to animate the route's exit before removing it from the
/// overlay).
///
/// Subclasses that return false from [finishedWhenPopped] are responsible for
/// calling [NavigatorState.finalizeRoute] themselves.
@protected
bool get finishedWhenPopped => true;
@override
bool didPop(T? result) {
final bool returnValue = super.didPop(result);
assert(returnValue);
if (finishedWhenPopped) {
navigator!.finalizeRoute(this);
}
return returnValue;
}
@override
void dispose() {
for (final OverlayEntry entry in _overlayEntries) {
entry.dispose();
}
_overlayEntries.clear();
super.dispose();
}
}
/// A route with entrance and exit transitions.
///
/// See also:
///
/// * [Route], which documents the meaning of the `T` generic type argument.
abstract class TransitionRoute<T> extends OverlayRoute<T> implements PredictiveBackRoute {
/// Creates a route that animates itself when it is pushed or popped.
TransitionRoute({
super.settings,
});
/// This future completes only once the transition itself has finished, after
/// the overlay entries have been removed from the navigator's overlay.
///
/// This future completes once the animation has been dismissed. That will be
/// after [popped], because [popped] typically completes before the animation
/// even starts, as soon as the route is popped.
Future<T?> get completed => _transitionCompleter.future;
final Completer<T?> _transitionCompleter = Completer<T?>();
/// Handle to the performance mode request.
///
/// When the route is animating, the performance mode is requested. It is then
/// disposed when the animation ends. Requesting [DartPerformanceMode.latency]
/// indicates to the engine that the transition is latency sensitive and to delay
/// non-essential work while this handle is active.
PerformanceModeRequestHandle? _performanceModeRequestHandle;
/// {@template flutter.widgets.TransitionRoute.transitionDuration}
/// The duration the transition going forwards.
///
/// See also:
///
/// * [reverseTransitionDuration], which controls the duration of the
/// transition when it is in reverse.
/// {@endtemplate}
Duration get transitionDuration;
/// {@template flutter.widgets.TransitionRoute.reverseTransitionDuration}
/// The duration the transition going in reverse.
///
/// By default, the reverse transition duration is set to the value of
/// the forwards [transitionDuration].
/// {@endtemplate}
Duration get reverseTransitionDuration => transitionDuration;
/// {@template flutter.widgets.TransitionRoute.opaque}
/// 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.
/// {@endtemplate}
bool get opaque;
/// {@template flutter.widgets.TransitionRoute.allowSnapshotting}
/// Whether the route transition will prefer to animate a snapshot of the
/// entering/exiting routes.
///
/// When this value is true, certain route transitions (such as the Android
/// zoom page transition) will snapshot the entering and exiting routes.
/// These snapshots are then animated in place of the underlying widgets to
/// improve performance of the transition.
///
/// Generally this means that animations that occur on the entering/exiting
/// route while the route animation plays may appear frozen - unless they
/// are a hero animation or something that is drawn in a separate overlay.
/// {@endtemplate}
bool get allowSnapshotting => true;
// 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.
@override
bool get finishedWhenPopped => _controller!.status == AnimationStatus.dismissed && !_popFinalized;
bool _popFinalized = false;
/// The animation that drives the route's transition and the previous route's
/// forward transition.
Animation<double>? get animation => _animation;
Animation<double>? _animation;
/// The animation controller that the route uses to drive the transitions.
///
/// The animation itself is exposed by the [animation] property.
@protected
AnimationController? get controller => _controller;
AnimationController? _controller;
/// 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.
Animation<double>? get secondaryAnimation => _secondaryAnimation;
final ProxyAnimation _secondaryAnimation = ProxyAnimation(kAlwaysDismissedAnimation);
/// 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;
/// Called to create the animation controller that will drive the transitions to
/// this route from the previous one, and back to the previous route from this
/// one.
///
/// The returned controller will be disposed by [AnimationController.dispose]
/// if the [willDisposeAnimationController] is `true`.
AnimationController createAnimationController() {
assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
final Duration duration = transitionDuration;
final Duration reverseDuration = reverseTransitionDuration;
assert(duration >= Duration.zero);
return AnimationController(
duration: duration,
reverseDuration: reverseDuration,
debugLabel: debugLabel,
vsync: navigator!,
);
}
/// Called to create the animation that exposes the current progress of
/// the transition controlled by the animation controller created by
/// [createAnimationController()].
Animation<double> createAnimation() {
assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
assert(_controller != null);
return _controller!.view;
}
T? _result;
void _handleStatusChanged(AnimationStatus status) {
switch (status) {
case AnimationStatus.completed:
if (overlayEntries.isNotEmpty) {
overlayEntries.first.opaque = opaque;
}
_performanceModeRequestHandle?.dispose();
_performanceModeRequestHandle = null;
case AnimationStatus.forward:
case AnimationStatus.reverse:
if (overlayEntries.isNotEmpty) {
overlayEntries.first.opaque = false;
}
_performanceModeRequestHandle ??=
SchedulerBinding.instance
.requestPerformanceMode(ui.DartPerformanceMode.latency);
case AnimationStatus.dismissed:
// We might still be an active route if a subclass is controlling the
// transition and hits the dismissed status. For example, the iOS
// back gesture drives this animation to the dismissed status before
// removing the route and disposing it.
if (!isActive) {
navigator!.finalizeRoute(this);
_popFinalized = true;
_performanceModeRequestHandle?.dispose();
_performanceModeRequestHandle = null;
}
}
}
@override
void install() {
assert(!_transitionCompleter.isCompleted, 'Cannot install a $runtimeType after disposing it.');
_controller = createAnimationController();
assert(_controller != null, '$runtimeType.createAnimationController() returned null.');
_animation = createAnimation()
..addStatusListener(_handleStatusChanged);
assert(_animation != null, '$runtimeType.createAnimation() returned null.');
super.install();
if (_animation!.isCompleted && overlayEntries.isNotEmpty) {
overlayEntries.first.opaque = opaque;
}
}
@override
TickerFuture didPush() {
assert(_controller != null, '$runtimeType.didPush called before calling install() or after calling dispose().');
assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
super.didPush();
return _controller!.forward();
}
@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();
_controller!.value = _controller!.upperBound;
}
@override
void didReplace(Route<dynamic>? oldRoute) {
assert(_controller != null, '$runtimeType.didReplace called before calling install() or after calling dispose().');
assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
if (oldRoute is TransitionRoute) {
_controller!.value = oldRoute._controller!.value;
}
super.didReplace(oldRoute);
}
@override
bool didPop(T? result) {
assert(_controller != null, '$runtimeType.didPop called before calling install() or after calling dispose().');
assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
_result = result;
_controller!.reverse();
return super.didPop(result);
}
@override
void didPopNext(Route<dynamic> nextRoute) {
assert(_controller != null, '$runtimeType.didPopNext called before calling install() or after calling dispose().');
assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
_updateSecondaryAnimation(nextRoute);
super.didPopNext(nextRoute);
}
@override
void didChangeNext(Route<dynamic>? nextRoute) {
assert(_controller != null, '$runtimeType.didChangeNext called before calling install() or after calling dispose().');
assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
_updateSecondaryAnimation(nextRoute);
super.didChangeNext(nextRoute);
}
// 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.
VoidCallback? _trainHoppingListenerRemover;
void _updateSecondaryAnimation(Route<dynamic>? nextRoute) {
// There is an existing train hopping in progress. Unfortunately, we cannot
// dispose current train hopping animation until we replace it with a new
// animation.
final VoidCallback? previousTrainHoppingListenerRemover = _trainHoppingListenerRemover;
_trainHoppingListenerRemover = null;
if (nextRoute is TransitionRoute<dynamic> && canTransitionTo(nextRoute) && nextRoute.canTransitionFrom(this)) {
final Animation<double>? current = _secondaryAnimation.parent;
if (current != null) {
final Animation<double> currentTrain = (current is TrainHoppingAnimation ? current.currentTrain : current)!;
final Animation<double> nextTrain = nextRoute._animation!;
if (
currentTrain.value == nextTrain.value ||
nextTrain.status == AnimationStatus.completed ||
nextTrain.status == AnimationStatus.dismissed
) {
_setSecondaryAnimation(nextTrain, nextRoute.completed);
} else {
// Two trains animate at different values. We have to do train hopping.
// There are three possibilities of train hopping:
// 1. We hop on the nextTrain when two trains meet in the middle using
// TrainHoppingAnimation.
// 2. There is no chance to hop on nextTrain because two trains never
// cross each other. We have to directly set the animation to
// nextTrain once the nextTrain stops animating.
// 3. A new _updateSecondaryAnimation is called before train hopping
// finishes. We leave a listener remover for the next call to
// properly clean up the existing train hopping.
TrainHoppingAnimation? newAnimation;
void jumpOnAnimationEnd(AnimationStatus status) {
switch (status) {
case AnimationStatus.completed:
case AnimationStatus.dismissed:
// The nextTrain has stopped animating without train hopping.
// Directly sets the secondary animation and disposes the
// TrainHoppingAnimation.
_setSecondaryAnimation(nextTrain, nextRoute.completed);
if (_trainHoppingListenerRemover != null) {
_trainHoppingListenerRemover!();
_trainHoppingListenerRemover = null;
}
case AnimationStatus.forward:
case AnimationStatus.reverse:
break;
}
}
_trainHoppingListenerRemover = () {
nextTrain.removeStatusListener(jumpOnAnimationEnd);
newAnimation?.dispose();
};
nextTrain.addStatusListener(jumpOnAnimationEnd);
newAnimation = TrainHoppingAnimation(
currentTrain,
nextTrain,
onSwitchedTrain: () {
assert(_secondaryAnimation.parent == newAnimation);
assert(newAnimation!.currentTrain == nextRoute._animation);
// We can hop on the nextTrain, so we don't need to listen to
// whether the nextTrain has stopped.
_setSecondaryAnimation(newAnimation!.currentTrain, nextRoute.completed);
if (_trainHoppingListenerRemover != null) {
_trainHoppingListenerRemover!();
_trainHoppingListenerRemover = null;
}
},
);
_setSecondaryAnimation(newAnimation, nextRoute.completed);
}
} else {
_setSecondaryAnimation(nextRoute._animation, nextRoute.completed);
}
} else {
_setSecondaryAnimation(kAlwaysDismissedAnimation);
}
// Finally, we dispose any previous train hopping animation because it
// has been successfully updated at this point.
if (previousTrainHoppingListenerRemover != null) {
previousTrainHoppingListenerRemover();
}
}
void _setSecondaryAnimation(Animation<double>? animation, [Future<dynamic>? disposed]) {
_secondaryAnimation.parent = animation;
// Releases the reference to the next route's animation when that route
// is disposed.
disposed?.then((dynamic _) {
if (_secondaryAnimation.parent == animation) {
_secondaryAnimation.parent = kAlwaysDismissedAnimation;
if (animation is TrainHoppingAnimation) {
animation.dispose();
}
}
});
}
/// 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.
///
/// Subclasses can override this method to restrict the set of routes they
/// need to coordinate transitions with.
///
/// If true, and `nextRoute.canTransitionFrom()` is true, then the
/// [ModalRoute.buildTransitions] `secondaryAnimation` will run from 0.0 - 1.0
/// 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.
///
/// If false, this route's [ModalRoute.buildTransitions] `secondaryAnimation` parameter
/// value will be [kAlwaysDismissedAnimation]. In other words, this route
/// will not animate when [nextRoute] is pushed on top of it or when
/// [nextRoute] is popped off of it.
///
/// Returns true by default.
///
/// See also:
///
/// * [canTransitionFrom], which must be true for [nextRoute] for the
/// [ModalRoute.buildTransitions] `secondaryAnimation` to run.
bool canTransitionTo(TransitionRoute<dynamic> nextRoute) => true;
/// 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.
///
/// Subclasses can override this method to restrict the set of routes they
/// need to coordinate transitions with.
///
/// If true, and `previousRoute.canTransitionTo()` is true, then the
/// previous route's [ModalRoute.buildTransitions] `secondaryAnimation` will
/// 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.
///
/// If false, then the previous route's [ModalRoute.buildTransitions]
/// `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
/// [ModalRoute.buildTransitions] `secondaryAnimation` to run.
bool canTransitionFrom(TransitionRoute<dynamic> previousRoute) => true;
// Begin PredictiveBackRoute.
@override
void handleStartBackGesture({double progress = 0.0}) {
assert(isCurrent);
_controller?.value = progress;
navigator?.didStartUserGesture();
}
@override
void handleUpdateBackGestureProgress({required double progress}) {
// If some other navigation happened during this gesture, don't mess with
// the transition anymore.
if (!isCurrent) {
return;
}
_controller?.value = progress;
}
@override
void handleCancelBackGesture() {
_handleDragEnd(animateForward: true);
}
@override
void handleCommitBackGesture() {
_handleDragEnd(animateForward: false);
}
void _handleDragEnd({required bool animateForward}) {
if (isCurrent) {
if (animateForward) {
// The closer the panel is to dismissing, the shorter the animation is.
// We want to cap the animation time, but we want to use a linear curve
// to determine it.
// These values were eyeballed to match the native predictive back
// animation on a Pixel 2 running Android API 34.
final int droppedPageForwardAnimationTime = min(
ui.lerpDouble(800, 0, _controller!.value)!.floor(),
300,
);
_controller?.animateTo(
1.0,
duration: Duration(milliseconds: droppedPageForwardAnimationTime),
curve: Curves.fastLinearToSlowEaseIn,
);
} else {
// This route is destined to pop at this point. Reuse navigator's pop.
navigator?.pop();
// The popping may have finished inline if already at the target destination.
if (_controller?.isAnimating ?? false) {
// Otherwise, use a custom popping animation duration and curve.
final int droppedPageBackAnimationTime =
ui.lerpDouble(0, 800, _controller!.value)!.floor();
_controller!.animateBack(0.0,
duration: Duration(milliseconds: droppedPageBackAnimationTime),
curve: Curves.fastLinearToSlowEaseIn);
}
}
}
if (_controller?.isAnimating ?? false) {
// Keep the userGestureInProgress in true state since AndroidBackGesturePageTransitionsBuilder
// depends on userGestureInProgress.
late final AnimationStatusListener animationStatusCallback;
animationStatusCallback = (AnimationStatus status) {
navigator?.didStopUserGesture();
_controller!.removeStatusListener(animationStatusCallback);
};
_controller!.addStatusListener(animationStatusCallback);
} else {
navigator?.didStopUserGesture();
}
}
// End PredictiveBackRoute.
@override
void dispose() {
assert(!_transitionCompleter.isCompleted, 'Cannot dispose a $runtimeType twice.');
_animation?.removeStatusListener(_handleStatusChanged);
_performanceModeRequestHandle?.dispose();
_performanceModeRequestHandle = null;
if (willDisposeAnimationController) {
_controller?.dispose();
}
_transitionCompleter.complete(_result);
super.dispose();
}
/// A short description of this route useful for debugging.
String get debugLabel => objectRuntimeType(this, 'TransitionRoute');
@override
String toString() => '${objectRuntimeType(this, 'TransitionRoute')}(animation: $_controller)';
}
/// An interface for a route that supports predictive back gestures.
///
/// See also:
///
/// * [PredictiveBackPageTransitionsBuilder], which builds page transitions for
/// predictive back.
abstract interface class PredictiveBackRoute {
/// Whether this route is the top-most route on the navigator.
bool get isCurrent;
/// Whether a pop gesture can be started by the user for this route.
bool get popGestureEnabled;
/// Handles a predictive back gesture starting.
///
/// The `progress` parameter indicates the progress of the gesture from 0.0 to
/// 1.0, as in [PredictiveBackEvent.progress].
void handleStartBackGesture({double progress = 0.0});
/// Handles a predictive back gesture updating as the user drags across the
/// screen.
///
/// The `progress` parameter indicates the progress of the gesture from 0.0 to
/// 1.0, as in [PredictiveBackEvent.progress].
void handleUpdateBackGestureProgress({required double progress});
/// Handles a predictive back gesture ending successfully.
void handleCommitBackGesture();
/// Handles a predictive back gesture ending in cancellation.
void handleCancelBackGesture();
}
/// An entry in the history of a [LocalHistoryRoute].
class LocalHistoryEntry {
/// Creates an entry in the history of a [LocalHistoryRoute].
///
/// The [impliesAppBarDismissal] defaults to true if not provided.
LocalHistoryEntry({ this.onRemove, this.impliesAppBarDismissal = true });
/// Called when this entry is removed from the history of its associated [LocalHistoryRoute].
final VoidCallback? onRemove;
LocalHistoryRoute<dynamic>? _owner;
/// Whether an [AppBar] in the route this entry belongs to should
/// automatically add a back button or close button.
///
/// Defaults to true.
final bool impliesAppBarDismissal;
/// Remove this entry from the history of its associated [LocalHistoryRoute].
void remove() {
_owner?.removeLocalHistoryEntry(this);
assert(_owner == null);
}
void _notifyRemoved() {
onRemove?.call();
}
}
/// A mixin used by routes to handle back navigations internally by popping a list.
///
/// When a [Navigator] is instructed to pop, the current route is given an
/// opportunity to handle the pop internally. A [LocalHistoryRoute] handles the
/// pop internally if its list of local history entries is non-empty. Rather
/// than being removed as the current route, the most recent [LocalHistoryEntry]
/// is removed from the list and its [LocalHistoryEntry.onRemove] is called.
///
/// See also:
///
/// * [Route], which documents the meaning of the `T` generic type argument.
mixin LocalHistoryRoute<T> on Route<T> {
List<LocalHistoryEntry>? _localHistory;
int _entriesImpliesAppBarDismissal = 0;
/// Adds a local history entry to this route.
///
/// When asked to pop, if this route has any local history entries, this route
/// 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.
///
/// {@tool snippet}
///
/// 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 {
/// const App({super.key});
///
/// @override
/// Widget build(BuildContext context) {
/// return MaterialApp(
/// initialRoute: '/',
/// routes: <String, WidgetBuilder>{
/// '/': (BuildContext context) => const HomePage(),
/// '/second_page': (BuildContext context) => const SecondPage(),
/// },
/// );
/// }
/// }
///
/// class HomePage extends StatefulWidget {
/// const HomePage({super.key});
///
/// @override
/// State<HomePage> createState() => _HomePageState();
/// }
///
/// class _HomePageState extends State<HomePage> {
/// @override
/// Widget build(BuildContext context) {
/// return Scaffold(
/// body: Center(
/// child: Column(
/// mainAxisSize: MainAxisSize.min,
/// children: <Widget>[
/// const Text('HomePage'),
/// // Press this button to open the SecondPage.
/// ElevatedButton(
/// child: const Text('Second Page >'),
/// onPressed: () {
/// Navigator.pushNamed(context, '/second_page');
/// },
/// ),
/// ],
/// ),
/// ),
/// );
/// }
/// }
///
/// class SecondPage extends StatefulWidget {
/// const SecondPage({super.key});
///
/// @override
/// State<SecondPage> createState() => _SecondPageState();
/// }
///
/// class _SecondPageState extends State<SecondPage> {
///
/// bool _showRectangle = false;
///
/// Future<void> _navigateLocallyToShowRectangle() async {
/// // 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);
/// ModalRoute.of(context)?.addLocalHistoryEntry(
/// LocalHistoryEntry(
/// onRemove: () {
/// // Hide the red rectangle.
/// setState(() => _showRectangle = false);
/// }
/// )
/// );
/// }
///
/// @override
/// Widget build(BuildContext context) {
/// final Widget localNavContent = _showRectangle
/// ? Container(
/// width: 100.0,
/// height: 100.0,
/// color: Colors.red,
/// )
/// : ElevatedButton(
/// onPressed: _navigateLocallyToShowRectangle,
/// child: const Text('Show Rectangle'),
/// );
///
/// return Scaffold(
/// body: Center(
/// child: Column(
/// mainAxisAlignment: MainAxisAlignment.center,
/// children: <Widget>[
/// localNavContent,
/// ElevatedButton(
/// child: const Text('< Back'),
/// onPressed: () {
/// // Pop a route. If this is pressed while the red rectangle is
/// // visible then it will pop our local history entry, which
/// // will hide the red rectangle. Otherwise, the SecondPage will
/// // navigate back to the HomePage.
/// Navigator.of(context).pop();
/// },
/// ),
/// ],
/// ),
/// ),
/// );
/// }
/// }
/// ```
/// {@end-tool}
void addLocalHistoryEntry(LocalHistoryEntry entry) {
assert(entry._owner == null);
entry._owner = this;
_localHistory ??= <LocalHistoryEntry>[];
final bool wasEmpty = _localHistory!.isEmpty;
_localHistory!.add(entry);
bool internalStateChanged = false;
if (entry.impliesAppBarDismissal) {
internalStateChanged = _entriesImpliesAppBarDismissal == 0;
_entriesImpliesAppBarDismissal += 1;
}
if (wasEmpty || internalStateChanged) {
changedInternalState();
}
}
/// Remove a local history entry from this route.
///
/// The entry's [LocalHistoryEntry.onRemove] callback, if any, will be called
/// synchronously.
void removeLocalHistoryEntry(LocalHistoryEntry entry) {
assert(entry._owner == this);
assert(_localHistory!.contains(entry));
bool internalStateChanged = false;
if (_localHistory!.remove(entry) && entry.impliesAppBarDismissal) {
_entriesImpliesAppBarDismissal -= 1;
internalStateChanged = _entriesImpliesAppBarDismissal == 0;
}
entry._owner = null;
entry._notifyRemoved();
if (_localHistory!.isEmpty || internalStateChanged) {
assert(_entriesImpliesAppBarDismissal == 0);
if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) {
// 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.
SchedulerBinding.instance.addPostFrameCallback((Duration duration) {
if (isActive) {
changedInternalState();
}
}, debugLabel: 'LocalHistoryRoute.changedInternalState');
} else {
changedInternalState();
}
}
}
@Deprecated(
'Use popDisposition instead. '
'This feature was deprecated after v3.12.0-1.0.pre.',
)
@override
Future<RoutePopDisposition> willPop() async {
if (willHandlePopInternally) {
return RoutePopDisposition.pop;
}
return super.willPop();
}
@override
RoutePopDisposition get popDisposition {
if (willHandlePopInternally) {
return RoutePopDisposition.pop;
}
return super.popDisposition;
}
@override
bool didPop(T? result) {
if (_localHistory != null && _localHistory!.isNotEmpty) {
final LocalHistoryEntry entry = _localHistory!.removeLast();
assert(entry._owner == this);
entry._owner = null;
entry._notifyRemoved();
bool internalStateChanged = false;
if (entry.impliesAppBarDismissal) {
_entriesImpliesAppBarDismissal -= 1;
internalStateChanged = _entriesImpliesAppBarDismissal == 0;
}
if (_localHistory!.isEmpty || internalStateChanged) {
changedInternalState();
}
return false;
}
return super.didPop(result);
}
@override
bool get willHandlePopInternally {
return _localHistory != null && _localHistory!.isNotEmpty;
}
}
class _DismissModalAction extends DismissAction {
_DismissModalAction(this.context);
final BuildContext context;
@override
bool isEnabled(DismissIntent intent) {
final ModalRoute<dynamic> route = ModalRoute.of<dynamic>(context)!;
return route.barrierDismissible;
}
@override
Object invoke(DismissIntent intent) {
return Navigator.of(context).maybePop();
}
}
class _ModalScopeStatus extends InheritedWidget {
const _ModalScopeStatus({
required this.isCurrent,
required this.canPop,
required this.impliesAppBarDismissal,
required this.route,
required super.child,
});
final bool isCurrent;
final bool canPop;
final bool impliesAppBarDismissal;
final Route<dynamic> route;
@override
bool updateShouldNotify(_ModalScopeStatus old) {
return isCurrent != old.isCurrent ||
canPop != old.canPop ||
impliesAppBarDismissal != old.impliesAppBarDismissal ||
route != old.route;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder description) {
super.debugFillProperties(description);
description.add(FlagProperty('isCurrent', value: isCurrent, ifTrue: 'active', ifFalse: 'inactive'));
description.add(FlagProperty('canPop', value: canPop, ifTrue: 'can pop'));
description.add(FlagProperty('impliesAppBarDismissal', value: impliesAppBarDismissal, ifTrue: 'implies app bar dismissal'));
}
}
class _ModalScope<T> extends StatefulWidget {
const _ModalScope({
super.key,
required this.route,
});
final ModalRoute<T> route;
@override
_ModalScopeState<T> createState() => _ModalScopeState<T>();
}
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.
Widget? _page;
// This is the combination of the two animations for the route.
late Listenable _listenable;
/// The node this scope will use for its root [FocusScope] widget.
final FocusScopeNode focusScopeNode = FocusScopeNode(
debugLabel: '$_ModalScopeState Focus Scope',
);
final ScrollController primaryScrollController = ScrollController();
@override
void initState() {
super.initState();
final List<Listenable> animations = <Listenable>[
if (widget.route.animation != null) widget.route.animation!,
if (widget.route.secondaryAnimation != null) widget.route.secondaryAnimation!,
];
_listenable = Listenable.merge(animations);
}
@override
void didUpdateWidget(_ModalScope<T> oldWidget) {
super.didUpdateWidget(oldWidget);
assert(widget.route == oldWidget.route);
_updateFocusScopeNode();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_page = null;
_updateFocusScopeNode();
}
void _updateFocusScopeNode() {
final TraversalEdgeBehavior traversalEdgeBehavior;
final ModalRoute<T> route = widget.route;
if (route.traversalEdgeBehavior != null) {
traversalEdgeBehavior = route.traversalEdgeBehavior!;
} else {
traversalEdgeBehavior = route.navigator!.widget.routeTraversalEdgeBehavior;
}
focusScopeNode.traversalEdgeBehavior = traversalEdgeBehavior;
if (route.isCurrent && _shouldRequestFocus) {
route.navigator!.focusNode.enclosingScope?.setFirstFocus(focusScopeNode);
}
}
void _forceRebuildPage() {
setState(() {
_page = null;
});
}
@override
void dispose() {
focusScopeNode.dispose();