-
Notifications
You must be signed in to change notification settings - Fork 30.1k
Expand file tree
/
Copy pathnavigator.dart
More file actions
6450 lines (6040 loc) · 236 KB
/
navigator.dart
File metadata and controls
6450 lines (6040 loc) · 236 KB
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.
/// @docImport 'package:flutter/cupertino.dart';
/// @docImport 'package:flutter/material.dart';
///
/// @docImport 'app.dart';
/// @docImport 'form.dart';
/// @docImport 'pages.dart';
/// @docImport 'pop_scope.dart';
/// @docImport 'router.dart';
/// @docImport 'will_pop_scope.dart';
library;
import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:developer' as developer;
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 'basic.dart';
import 'binding.dart';
import 'focus_manager.dart';
import 'focus_scope.dart';
import 'focus_traversal.dart';
import 'framework.dart';
import 'heroes.dart';
import 'notification_listener.dart';
import 'overlay.dart';
import 'restoration.dart';
import 'restoration_properties.dart';
import 'routes.dart';
import 'ticker_provider.dart';
// Duration for delay before refocusing in android so that the focus won't be interrupted.
const Duration _kAndroidRefocusingDelayDuration = Duration(milliseconds: 300);
// Examples can assume:
// typedef MyAppHome = Placeholder;
// typedef MyHomePage = Placeholder;
// typedef MyPage = ListTile; // any const widget with a Widget "title" constructor argument would do
// late NavigatorState navigator;
// late BuildContext context;
/// Creates a route for the given route settings.
///
/// Used by [Navigator.onGenerateRoute].
///
/// See also:
///
/// * [Navigator], which is where all the [Route]s end up.
typedef RouteFactory = Route<dynamic>? Function(RouteSettings settings);
/// Creates a series of one or more routes.
///
/// Used by [Navigator.onGenerateInitialRoutes].
typedef RouteListFactory =
List<Route<dynamic>> Function(NavigatorState navigator, String initialRoute);
/// Creates a [Route] that is to be added to a [Navigator].
///
/// The route can be configured with the provided `arguments`. The provided
/// `context` is the `BuildContext` of the [Navigator] to which the route is
/// added.
///
/// Used by the restorable methods of the [Navigator] that add anonymous routes
/// (e.g. [NavigatorState.restorablePush]). For this use case, the
/// [RestorableRouteBuilder] must be static function annotated with
/// `@pragma('vm:entry-point')`. The [Navigator] will call it again during
/// state restoration to re-create the route.
typedef RestorableRouteBuilder<T> = Route<T> Function(BuildContext context, Object? arguments);
/// Signature for the [Navigator.popUntil] predicate argument.
typedef RoutePredicate = bool Function(Route<dynamic> route);
/// Signature for a callback that verifies that it's OK to call [Navigator.pop].
///
/// Used by [Form.onWillPop], [ModalRoute.addScopedWillPopCallback],
/// [ModalRoute.removeScopedWillPopCallback], and [WillPopScope].
@Deprecated(
'Use PopInvokedCallback instead. '
'This feature was deprecated after v3.12.0-1.0.pre.',
)
typedef WillPopCallback = Future<bool> Function();
/// Signature for the [Navigator.onPopPage] callback.
///
/// This callback must call [Route.didPop] on the specified route and must
/// properly update the pages list the next time it is passed into
/// [Navigator.pages] so that it no longer includes the corresponding [Page].
/// (Otherwise, the page will be interpreted as a new page to show when the
/// [Navigator.pages] list is next updated.)
typedef PopPageCallback = bool Function(Route<dynamic> route, dynamic result);
/// Signature for the [Navigator.onDidRemovePage] callback.
///
/// This must properly update the pages list the next time it is passed into
/// [Navigator.pages] so that it no longer includes the input `page`.
/// (Otherwise, the page will be interpreted as a new page to show when the
/// [Navigator.pages] list is next updated.)
typedef DidRemovePageCallback = void Function(Page<Object?> page);
/// Indicates whether the current route should be popped.
///
/// Used as the return value for [Route.willPop].
///
/// See also:
///
/// * [WillPopScope], a widget that hooks into the route's [Route.willPop]
/// mechanism.
enum RoutePopDisposition {
/// Pop the route.
///
/// If [Route.willPop] or [Route.popDisposition] return [pop] then the back
/// button will actually pop the current route.
pop,
/// Do not pop the route.
///
/// If [Route.willPop] or [Route.popDisposition] return [doNotPop] then the
/// back button will be ignored.
doNotPop,
/// Delegate this to the next level of navigation.
///
/// If [Route.willPop] or [Route.popDisposition] return [bubble] then the back
/// button will be handled by the [SystemNavigator], which will usually close
/// the application.
bubble,
}
/// An abstraction for an entry managed by a [Navigator].
///
/// This class defines an abstract interface between the navigator and the
/// "routes" that are pushed on and popped off the navigator. Most routes have
/// visual affordances, which they place in the navigators [Overlay] using one
/// or more [OverlayEntry] objects.
///
/// See [Navigator] for more explanation of how to use a [Route] with
/// navigation, including code examples.
///
/// See [MaterialPageRoute] for a route that replaces the entire screen with a
/// platform-adaptive transition.
///
/// A route can belong to a page if the [settings] are a subclass of [Page]. A
/// page-based route, as opposed to a pageless route, is created from
/// [Page.createRoute] during [Navigator.pages] updates. The page associated
/// with this route may change during the lifetime of the route. If the
/// [Navigator] updates the page of this route, it calls [changedInternalState]
/// to notify the route that the page has been updated.
///
/// The type argument `T` is the route's return type, as used by
/// [currentResult], [popped], and [didPop]. The type `void` may be used if the
/// route does not return a value.
abstract class Route<T> extends _RoutePlaceholder {
/// Initialize the [Route].
///
/// If the [settings] are not provided, an empty [RouteSettings] object is
/// used instead.
///
/// {@template flutter.widgets.navigator.Route.requestFocus}
/// If [requestFocus] is not provided, the value of [Navigator.requestFocus] is
/// used instead.
/// {@endtemplate}
Route({RouteSettings? settings, bool? requestFocus})
: _settings = settings ?? const RouteSettings(),
_requestFocus = requestFocus {
assert(debugMaybeDispatchCreated('widgets', 'Route<T>', this));
}
/// When the route state is updated, request focus if the current route is at the top.
///
/// If not provided in the constructor, [Navigator.requestFocus] is used instead.
bool get requestFocus => _requestFocus ?? navigator?.widget.requestFocus ?? false;
final bool? _requestFocus;
/// The navigator that the route is in, if any.
NavigatorState? get navigator => _navigator;
NavigatorState? _navigator;
bool get _installed => _navigator != null;
bool _isInstalledIn(NavigatorState state) => _navigator == state;
/// The settings for this route.
///
/// See [RouteSettings] for details.
///
/// The settings can change during the route's lifetime. If the settings
/// change, the route's overlays will be marked dirty (see
/// [changedInternalState]).
///
/// If the route is created from a [Page] in the [Navigator.pages] list, then
/// this will be a [Page] subclass, and it will be updated each time its
/// corresponding [Page] in the [Navigator.pages] has changed. Once the
/// [Route] is removed from the history, this value stops updating (and
/// remains with its last value).
RouteSettings get settings => _settings;
RouteSettings _settings;
bool get _isPageBased => settings is Page<Object?>;
/// The restoration scope ID to be used for the [RestorationScope] surrounding
/// this route.
///
/// The restoration scope ID is null if restoration is currently disabled
/// for this route.
///
/// If the restoration scope ID changes (e.g. because restoration is enabled
/// or disabled) during the life of the route, the [ValueListenable] notifies
/// its listeners. As an example, the ID changes to null while the route is
/// transitioning off screen, which triggers a notification on this field. At
/// that point, the route is considered as no longer present for restoration
/// purposes and its state will not be restored.
ValueListenable<String?> get restorationScopeId => _restorationScopeId;
final ValueNotifier<String?> _restorationScopeId = ValueNotifier<String?>(null);
void _updateSettings(RouteSettings newSettings) {
if (_settings != newSettings) {
_settings = newSettings;
if (_installed) {
changedInternalState();
}
}
}
// ignore: use_setters_to_change_properties, (setters can't be private)
void _updateRestorationId(String? restorationId) {
_restorationScopeId.value = restorationId;
}
/// The overlay entries of this route.
///
/// These are typically populated by [install]. The [Navigator] is in charge
/// of adding them to and removing them from the [Overlay].
///
/// There must be at least one entry in this list after [install] has been
/// invoked.
///
/// The [Navigator] will take care of keeping the entries together if the
/// route is moved in the history.
List<OverlayEntry> get overlayEntries => const <OverlayEntry>[];
/// Called when the route is inserted into the navigator.
///
/// Uses this to populate [overlayEntries]. There must be at least one entry in
/// this list after [install] has been invoked. The [Navigator] will be in charge
/// to add them to the [Overlay] or remove them from it by calling
/// [OverlayEntry.remove].
@protected
@mustCallSuper
void install() {}
/// Called after [install] when the route is pushed onto the navigator.
///
/// The returned value resolves when the push transition is complete.
///
/// The [didAdd] method will be called instead of [didPush] when the route
/// immediately appears on screen without any push transition.
///
/// The [didChangeNext] and [didChangePrevious] methods are typically called
/// immediately after this method is called.
@protected
@mustCallSuper
TickerFuture didPush() {
return TickerFuture.complete()..then<void>((void _) {
if (requestFocus) {
navigator!.focusNode.enclosingScope?.requestFocus();
}
});
}
/// Called after [install] when the route is added to the navigator.
///
/// This method is called instead of [didPush] when the route immediately
/// appears on screen without any push transition.
///
/// The [didChangeNext] and [didChangePrevious] methods are typically called
/// immediately after this method is called.
@protected
@mustCallSuper
void didAdd() {
if (requestFocus) {
// This TickerFuture serves two purposes. First, we want to make sure that
// animations triggered by other operations will finish before focusing
// the navigator. Second, navigator.focusNode might acquire more focused
// children in Route.install asynchronously. This TickerFuture will wait
// for it to finish first.
//
// The later case can be found when subclasses manage their own focus scopes.
// For example, ModalRoute creates a focus scope in its overlay entries. The
// focused child can only be attached to navigator after initState which
// will be guarded by the asynchronous gap.
TickerFuture.complete().then<void>((void _) {
// The route can be disposed before the ticker future completes. This can
// happen when the navigator is under a TabView that warps from one tab to
// another, non-adjacent tab, with an animation. The TabView reorders its
// children before and after the warping completes, and that causes its
// children to be built and disposed within the same frame. If one of its
// children contains a navigator, the routes in that navigator are also
// added and disposed within that frame.
//
// Since the reference to the navigator will be set to null after it is
// disposed, we have to do a null-safe operation in case that happens
// within the same frame when it is added.
navigator?.focusNode.enclosingScope?.requestFocus();
});
}
}
/// Called after [install] when the route replaced another in the navigator.
///
/// The [didChangeNext] and [didChangePrevious] methods are typically called
/// immediately after this method is called.
@protected
@mustCallSuper
void didReplace(Route<dynamic>? oldRoute) {}
/// Returns whether calling [Navigator.maybePop] when this [Route] is current
/// ([isCurrent]) should do anything.
///
/// [Navigator.maybePop] is usually used instead of [Navigator.pop] to handle
/// the system back button.
///
/// By default, if a [Route] is the first route in the history (i.e., if
/// [isFirst]), it reports that pops should be bubbled
/// ([RoutePopDisposition.bubble]). This behavior prevents the user from
/// popping the first route off the history and being stranded at a blank
/// screen; instead, the larger scope is popped (e.g. the application quits,
/// so that the user returns to the previous application).
///
/// In other cases, the default behavior is to accept the pop
/// ([RoutePopDisposition.pop]).
///
/// The third possible value is [RoutePopDisposition.doNotPop], which causes
/// the pop request to be ignored entirely.
///
/// See also:
///
/// * [Form], which provides a [Form.onWillPop] callback that uses this
/// mechanism.
/// * [WillPopScope], another widget that provides a way to intercept the
/// back button.
@Deprecated(
'Use popDisposition instead. '
'This feature was deprecated after v3.12.0-1.0.pre.',
)
Future<RoutePopDisposition> willPop() async {
return isFirst ? RoutePopDisposition.bubble : RoutePopDisposition.pop;
}
/// Returns whether calling [Navigator.maybePop] when this [Route] is current
/// ([isCurrent]) should do anything.
///
/// [Navigator.maybePop] is usually used instead of [Navigator.pop] to handle
/// the system back button, when it hasn't been disabled via
/// [SystemNavigator.setFrameworkHandlesBack].
///
/// By default, if a [Route] is the first route in the history (i.e., if
/// [isFirst]), it reports that pops should be bubbled
/// ([RoutePopDisposition.bubble]). This behavior prevents the user from
/// popping the first route off the history and being stranded at a blank
/// screen; instead, the larger scope is popped (e.g. the application quits,
/// so that the user returns to the previous application).
///
/// In other cases, the default behavior is to accept the pop
/// ([RoutePopDisposition.pop]).
///
/// The third possible value is [RoutePopDisposition.doNotPop], which causes
/// the pop request to be ignored entirely.
///
/// See also:
///
/// * [Form], which provides a [Form.canPop] boolean that is similar.
/// * [PopScope], a widget that provides a way to intercept the back button.
/// * [Page.canPop], a way for [Page] to affect this property.
RoutePopDisposition get popDisposition {
if (_isPageBased) {
final page = settings as Page<Object?>;
if (!page.canPop) {
return RoutePopDisposition.doNotPop;
}
}
return isFirst ? RoutePopDisposition.bubble : RoutePopDisposition.pop;
}
/// Called after a route pop was handled.
///
/// Even when the pop is canceled, for example by a [PopScope] widget, this
/// will still be called. The `didPop` parameter indicates whether or not the
/// back navigation actually happened successfully.
@Deprecated(
'Override onPopInvokedWithResult instead. '
'This feature was deprecated after v3.22.0-12.0.pre.',
)
void onPopInvoked(bool didPop) {}
/// {@template flutter.widgets.navigator.onPopInvokedWithResult}
/// Called after a route pop was handled.
///
/// Even when the pop is canceled, for example by a [PopScope] widget, this
/// will still be called. The `didPop` parameter indicates whether or not the
/// back navigation actually happened successfully.
/// {@endtemplate}
@mustCallSuper
void onPopInvokedWithResult(bool didPop, T? result) {
if (_isPageBased) {
final page = settings as Page<T>;
page.onPopInvoked(didPop, result);
}
}
/// Whether calling [didPop] would return false.
bool get willHandlePopInternally => false;
/// When this route is popped (see [Navigator.pop]) if the result isn't
/// specified or if it's null, this value will be used instead.
///
/// This fallback is implemented by [didComplete]. This value is used if the
/// argument to that method is null.
T? get currentResult => null;
/// A future that completes when this route is popped off the navigator.
///
/// The future completes with the value given to [Navigator.pop], if any, or
/// else the value of [currentResult]. See [didComplete] for more discussion
/// on this topic.
Future<T?> get popped => _popCompleter.future;
final Completer<T?> _popCompleter = Completer<T?>();
final Completer<T?> _disposeCompleter = Completer<T?>();
/// A request was made to pop this route. If the route can handle it
/// internally (e.g. because it has its own stack of internal state) then
/// return false, otherwise return true (by returning the value of calling
/// `super.didPop`). Returning false will prevent the default behavior of
/// [NavigatorState.pop].
///
/// When this function returns true, the navigator removes this route from
/// the history but does not yet call [dispose]. Instead, it is the route's
/// responsibility to call [NavigatorState.finalizeRoute], which will in turn
/// call [dispose] on the route. This sequence lets the route perform an
/// exit animation (or some other visual effect) after being popped but prior
/// to being disposed.
///
/// This method should call [didComplete] to resolve the [popped] future (and
/// this is all that the default implementation does); routes should not wait
/// for their exit animation to complete before doing so.
///
/// See [popped], [didComplete], and [currentResult] for a discussion of the
/// `result` argument.
@mustCallSuper
bool didPop(T? result) {
didComplete(result);
return true;
}
/// The route was popped or is otherwise being removed somewhat gracefully.
///
/// This is called by [didPop] and in response to
/// [NavigatorState.pushReplacement]. If [didPop] was not called, then the
/// [NavigatorState.finalizeRoute] method must be called immediately, and no exit
/// animation will run.
///
/// The [popped] future is completed by this method. The `result` argument
/// specifies the value that this future is completed with, unless it is null,
/// in which case [currentResult] is used instead.
///
/// This should be called before the pop animation, if any, takes place,
/// though in some cases the animation may be driven by the user before the
/// route is committed to being popped; this can in particular happen with the
/// iOS-style back gesture. See [NavigatorState.didStartUserGesture].
@protected
@mustCallSuper
void didComplete(T? result) {
_popCompleter.complete(result ?? currentResult);
}
/// The given route, which was above this one, has been popped off the
/// navigator.
///
/// This route is now the current route ([isCurrent] is now true), and there
/// is no next route.
@protected
@mustCallSuper
void didPopNext(Route<dynamic> nextRoute) {}
/// This route's next route has changed to the given new route.
///
/// This is called on a route whenever the next route changes for any reason,
/// so long as it is in the history, including when a route is first added to
/// a [Navigator] (e.g. by [Navigator.push]), except for cases when
/// [didPopNext] would be called.
///
/// The `nextRoute` argument will be null if there's no new next route (i.e.
/// if [isCurrent] is true).
@protected
@mustCallSuper
void didChangeNext(Route<dynamic>? nextRoute) {}
/// This route's previous route has changed to the given new route.
///
/// This is called on a route whenever the previous route changes for any
/// reason, so long as it is in the history, except for immediately after the
/// route itself has been pushed (in which case [didPush] or [didReplace] will
/// be called instead).
///
/// The `previousRoute` argument will be null if there's no previous route
/// (i.e. if [isFirst] is true).
@protected
@mustCallSuper
void didChangePrevious(Route<dynamic>? previousRoute) {}
/// Called whenever the internal state of the route has changed.
///
/// This should be called whenever [willHandlePopInternally], [didPop],
/// [ModalRoute.offstage], or other internal state of the route changes value.
/// It is used by [ModalRoute], for example, to report the new information via
/// its inherited widget to any children of the route.
///
/// See also:
///
/// * [changedExternalState], which is called when the [Navigator] has
/// updated in some manner that might affect the routes.
@protected
@mustCallSuper
void changedInternalState() {}
/// Called whenever the [Navigator] has updated in some manner that might
/// affect routes, to indicate that the route may wish to rebuild as well.
///
/// This is called by the [Navigator] whenever the
/// [NavigatorState]'s [State.widget] changes (as in [State.didUpdateWidget]),
/// for example because the [MaterialApp] has been rebuilt. This
/// ensures that routes that directly refer to the state of the
/// widget that built the [MaterialApp] will be notified when that
/// widget rebuilds, since it would otherwise be difficult to notify
/// the routes that state they depend on may have changed.
///
/// It is also called whenever the [Navigator]'s dependencies change
/// (as in [State.didChangeDependencies]). This allows routes to use the
/// [Navigator]'s context ([NavigatorState.context]), for example in
/// [ModalRoute.barrierColor], and update accordingly.
///
/// The [ModalRoute] subclass overrides this to force the barrier
/// overlay to rebuild.
///
/// See also:
///
/// * [changedInternalState], the equivalent but for changes to the internal
/// state of the route.
@protected
@mustCallSuper
void changedExternalState() {}
/// Discards any resources used by the object.
///
/// This method should not remove its [overlayEntries] from the [Overlay]. The
/// object's owner is in charge of doing that.
///
/// After this is called, the object is not in a usable state and should be
/// discarded.
///
/// This method should only be called by the object's owner; typically the
/// [Navigator] owns a route and so will call this method when the route is
/// removed, after which the route is no longer referenced by the navigator.
@mustCallSuper
@protected
void dispose() {
_navigator = null;
_restorationScopeId.dispose();
_disposeCompleter.complete();
assert(debugMaybeDispatchDisposed(this));
}
/// Whether this route is the top-most route on the navigator.
///
/// If this is true, then [isActive] is also true.
bool get isCurrent {
if (!_installed) {
return false;
}
final _RouteEntry? currentRouteEntry = _navigator!._lastRouteEntryWhereOrNull(
_RouteEntry.isPresentPredicate,
);
if (currentRouteEntry == null) {
return false;
}
return currentRouteEntry.route == this;
}
/// Whether this route is the bottom-most active route on the navigator.
///
/// If [isFirst] and [isCurrent] are both true then this is the only route on
/// the navigator (and [isActive] will also be true).
bool get isFirst {
if (!_installed) {
return false;
}
final _RouteEntry? currentRouteEntry = _navigator!._firstRouteEntryWhereOrNull(
_RouteEntry.isPresentPredicate,
);
if (currentRouteEntry == null) {
return false;
}
return currentRouteEntry.route == this;
}
/// Whether there is at least one active route underneath this route.
@protected
bool get hasActiveRouteBelow {
if (!_installed) {
return false;
}
for (final _RouteEntry entry in _navigator!._history) {
if (entry.route == this) {
return false;
}
if (_RouteEntry.isPresentPredicate(entry)) {
return true;
}
}
return false;
}
/// Whether this route is on the navigator.
///
/// If the route is not only active, but also the current route (the top-most
/// route), then [isCurrent] will also be true. If it is the first route (the
/// bottom-most route), then [isFirst] will also be true.
///
/// If a higher route is entirely opaque, then the route will be active but not
/// rendered. It is even possible for the route to be active but for the stateful
/// widgets within the route to not be instantiated. See [ModalRoute.maintainState].
bool get isActive {
return _navigator?._firstRouteEntryWhereOrNull(_RouteEntry.isRoutePredicate(this))?.isPresent ??
false;
}
}
/// Data that might be useful in constructing a [Route].
@immutable
class RouteSettings {
/// Creates data used to construct routes.
const RouteSettings({this.name, this.arguments});
/// The name of the route (e.g., "/settings").
///
/// If null, the route is anonymous.
final String? name;
/// The arguments passed to this route.
///
/// May be used when building the route, e.g. in [Navigator.onGenerateRoute].
final Object? arguments;
@override
String toString() =>
'${objectRuntimeType(this, 'RouteSettings')}(${name == null ? 'none' : '"$name"'}, $arguments)';
}
/// Describes the configuration of a [Route].
///
/// The type argument `T` is the corresponding [Route]'s return type, as
/// used by [Route.currentResult], [Route.popped], and [Route.didPop].
///
/// The [canPop] and [onPopInvoked] are used for intercepting pops.
///
/// {@tool dartpad}
/// This sample demonstrates how to use this [canPop] and [onPopInvoked] to
/// intercept pops.
///
/// ** See code in examples/api/lib/widgets/page/page_can_pop.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [Navigator.pages], which accepts a list of [Page]s and updates its routes
/// history.
abstract class Page<T> extends RouteSettings {
/// Creates a page and initializes [key] for subclasses.
const Page({
this.key,
super.name,
super.arguments,
this.restorationId,
this.canPop = true,
this.onPopInvoked = _defaultPopInvokedHandler,
});
static void _defaultPopInvokedHandler(bool didPop, Object? result) {}
/// The key associated with this page.
///
/// This key will be used for comparing pages in [canUpdate].
final LocalKey? key;
/// Restoration ID to save and restore the state of the [Route] configured by
/// this page.
///
/// If no restoration ID is provided, the [Route] will not restore its state.
///
/// See also:
///
/// * [RestorationManager], which explains how state restoration works in
/// Flutter.
final String? restorationId;
/// Called after a pop on the associated route was handled.
///
/// It's not possible to prevent the pop from happening at the time that this
/// method is called; the pop has already happened. Use [canPop] to
/// disable pops in advance.
///
/// This will still be called even when the pop is canceled. A pop is canceled
/// when the associated [Route.popDisposition] returns false, or when
/// [canPop] is set to false. The `didPop` parameter indicates whether or not
/// the back navigation actually happened successfully.
final PopInvokedWithResultCallback<T> onPopInvoked;
/// When false, blocks the associated route from being popped.
///
/// If this is set to false for first page in the Navigator. It prevents
/// Flutter app from exiting.
///
/// If there are any [PopScope] widgets in a route's widget subtree,
/// each of their `canPop` must be `true`, in addition to this canPop, in
/// order for the route to be able to pop.
final bool canPop;
/// Whether this page can be updated with the [other] page.
///
/// Two pages are consider updatable if they have same the [runtimeType] and
/// [key].
bool canUpdate(Page<dynamic> other) {
return other.runtimeType == runtimeType && other.key == key;
}
/// Creates the [Route] that corresponds to this page.
///
/// The created [Route] must have its [Route.settings] property set to this [Page].
@factory
Route<T> createRoute(BuildContext context);
@override
String toString() => '${objectRuntimeType(this, 'Page')}("$name", $key, $arguments)';
}
/// An interface for observing the behavior of a [Navigator].
class NavigatorObserver {
/// The navigator that the observer is observing, if any.
NavigatorState? get navigator => _navigators[this];
// Expando mapping instances of NavigatorObserver to their associated
// NavigatorState (or `null`, if there is no associated NavigatorState). The
// reason we don't use a private instance field of type
// `NavigatorState?` is because as part of implementing
// https://github.com/dart-lang/language/issues/2020, it will soon become a
// runtime error to invoke a private member that is mocked in another
// library. By using an expando rather than an instance field, we ensure
// that a mocked NavigatorObserver can still properly keep track of its
// associated NavigatorState.
static final Expando<NavigatorState> _navigators = Expando<NavigatorState>();
/// The [Navigator] pushed `route`.
///
/// The route immediately below that one, and thus the previously active
/// route, is `previousRoute`.
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {}
/// The [Navigator] popped `route`.
///
/// The route immediately below that one, and thus the newly active
/// route, is `previousRoute`.
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {}
/// The [Navigator] removed `route`.
///
/// If only one route is being removed, then the route immediately below
/// that one, if any, is `previousRoute`.
///
/// If multiple routes are being removed, then the route below the
/// bottommost route being removed, if any, is `previousRoute`, and this
/// method will be called once for each removed route, from the topmost route
/// to the bottommost route.
void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {}
/// The [Navigator] replaced `oldRoute` with `newRoute`.
void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {}
/// The top most route has changed.
///
/// The `topRoute` is the new top most route. This can be a new route pushed
/// on top of the screen, or an existing route that becomes the new top-most
/// route because the previous top-most route has been popped.
///
/// The `previousTopRoute` was the top most route before the change. This can
/// be a route that was popped off the screen, or a route that will be covered
/// by the `topRoute`. This can also be null if this is the first build.
void didChangeTop(Route<dynamic> topRoute, Route<dynamic>? previousTopRoute) {}
/// The [Navigator]'s routes are being moved by a user gesture.
///
/// For example, this is called when an iOS back gesture starts, and is used
/// to disable hero animations during such interactions.
void didStartUserGesture(Route<dynamic> route, Route<dynamic>? previousRoute) {}
/// User gesture is no longer controlling the [Navigator].
///
/// Paired with an earlier call to [didStartUserGesture].
void didStopUserGesture() {}
}
/// An inherited widget to host a hero controller.
///
/// The hosted hero controller will be picked up by the navigator in the
/// [child] subtree. Once a navigator picks up this controller, the navigator
/// will bar any navigator below its subtree from receiving this controller.
///
/// The hero controller inside the [HeroControllerScope] can only subscribe to
/// one navigator at a time. An assertion will be thrown if the hero controller
/// subscribes to more than one navigators. This can happen when there are
/// multiple navigators under the same [HeroControllerScope] in parallel.
class HeroControllerScope extends InheritedWidget {
/// Creates a widget to host the input [controller].
const HeroControllerScope({
super.key,
required HeroController this.controller,
required super.child,
});
/// Creates a widget to prevent the subtree from receiving the hero controller
/// above.
const HeroControllerScope.none({super.key, required super.child}) : controller = null;
/// The hero controller that is hosted inside this widget.
final HeroController? controller;
/// Retrieves the [HeroController] from the closest [HeroControllerScope]
/// ancestor, or null if none exists.
///
/// Calling this method will create a dependency on the closest
/// [HeroControllerScope] in the [context], if there is one.
///
/// See also:
///
/// * [HeroControllerScope.of], which is similar to this method, but asserts
/// if no [HeroControllerScope] ancestor is found.
static HeroController? maybeOf(BuildContext context) {
final HeroControllerScope? host = context
.dependOnInheritedWidgetOfExactType<HeroControllerScope>();
return host?.controller;
}
/// Retrieves the [HeroController] from the closest [HeroControllerScope]
/// ancestor.
///
/// If no ancestor is found, this method will assert in debug mode, and throw
/// an exception in release mode.
///
/// Calling this method will create a dependency on the closest
/// [HeroControllerScope] in the [context].
///
/// See also:
///
/// * [HeroControllerScope.maybeOf], which is similar to this method, but
/// returns null if no [HeroControllerScope] ancestor is found.
static HeroController of(BuildContext context) {
final HeroController? controller = maybeOf(context);
assert(() {
if (controller == null) {
throw FlutterError(
'HeroControllerScope.of() was called with a context that does not contain a '
'HeroControllerScope widget.\n'
'No HeroControllerScope widget ancestor could be found starting from the '
'context that was passed to HeroControllerScope.of(). This can happen '
'because you are using a widget that looks for a HeroControllerScope '
'ancestor, but no such ancestor exists.\n'
'The context used was:\n'
' $context',
);
}
return true;
}());
return controller!;
}
@override
bool updateShouldNotify(HeroControllerScope oldWidget) {
return oldWidget.controller != controller;
}
}
/// A [Route] wrapper interface that can be staged for [TransitionDelegate] to
/// decide how its underlying [Route] should transition on or off screen.
abstract class RouteTransitionRecord {
/// Retrieves the wrapped [Route].
Route<dynamic> get route;
/// Whether this route is waiting for the decision on how to enter the screen.
///
/// If this property is true, this route requires an explicit decision on how
/// to transition into the screen. Such a decision should be made in the
/// [TransitionDelegate.resolve].
bool get isWaitingForEnteringDecision;
/// Whether this route is waiting for the decision on how to exit the screen.
///
/// If this property is true, this route requires an explicit decision on how
/// to transition off the screen. Such a decision should be made in the
/// [TransitionDelegate.resolve].
bool get isWaitingForExitingDecision;
/// Marks the [route] to be pushed with transition.
///
/// During [TransitionDelegate.resolve], this can be called on an entering
/// route (where [RouteTransitionRecord.isWaitingForEnteringDecision] is true) in indicate that the
/// route should be pushed onto the [Navigator] with an animated transition.
void markForPush();
/// Marks the [route] to be added without transition.
///
/// During [TransitionDelegate.resolve], this can be called on an entering
/// route (where [RouteTransitionRecord.isWaitingForEnteringDecision] is true) in indicate that the
/// route should be added onto the [Navigator] without an animated transition.
void markForAdd();
/// Marks the [route] to be popped with transition.
///
/// During [TransitionDelegate.resolve], this can be called on an exiting
/// route to indicate that the route should be popped off the [Navigator] with
/// an animated transition.
void markForPop([dynamic result]);
/// Marks the [route] to be completed without transition.
///
/// During [TransitionDelegate.resolve], this can be called on an exiting
/// route to indicate that the route should be completed with the provided
/// result and removed from the [Navigator] without an animated transition.
void markForComplete([dynamic result]);
/// Marks the [route] to be removed without transition.
///
/// During [TransitionDelegate.resolve], this can be called on an exiting
/// route to indicate that the route should be removed from the [Navigator]
/// without completing and without an animated transition.
@Deprecated(
'Call markForComplete instead. '
'This will let route associated future to complete when route is removed. '
'This feature was deprecated after v3.27.0-1.0.pre.',
)
void markForRemove() => markForComplete();
}
/// The delegate that decides how pages added and removed from [Navigator.pages]
/// transition in or out of the screen.
///
/// This abstract class implements the API to be called by [Navigator] when it
/// requires explicit decisions on how the routes transition on or off the screen.
///
/// To make route transition decisions, subclass must implement [resolve].
///
/// {@tool snippet}
/// The following example demonstrates how to implement a subclass that always
/// removes or adds routes without animated transitions and puts the removed
/// routes at the top of the list.
///
/// ```dart
/// class NoAnimationTransitionDelegate extends TransitionDelegate<void> {
/// @override
/// Iterable<RouteTransitionRecord> resolve({
/// required List<RouteTransitionRecord> newPageRouteHistory,
/// required Map<RouteTransitionRecord?, RouteTransitionRecord> locationToExitingPageRoute,
/// required Map<RouteTransitionRecord?, List<RouteTransitionRecord>> pageRouteToPagelessRoutes,
/// }) {
/// final List<RouteTransitionRecord> results = <RouteTransitionRecord>[];
///
/// for (final RouteTransitionRecord pageRoute in newPageRouteHistory) {
/// if (pageRoute.isWaitingForEnteringDecision) {
/// pageRoute.markForAdd();
/// }
/// results.add(pageRoute);
///
/// }
/// for (final RouteTransitionRecord exitingPageRoute in locationToExitingPageRoute.values) {
/// if (exitingPageRoute.isWaitingForExitingDecision) {
/// exitingPageRoute.markForComplete();
/// final List<RouteTransitionRecord>? pagelessRoutes = pageRouteToPagelessRoutes[exitingPageRoute];
/// if (pagelessRoutes != null) {
/// for (final RouteTransitionRecord pagelessRoute in pagelessRoutes) {
/// pagelessRoute.markForComplete();
/// }
/// }
/// }
/// results.add(exitingPageRoute);