-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
route.dart
1434 lines (1305 loc) · 51.8 KB
/
route.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 2013 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 'package:collection/collection.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:meta/meta.dart';
import 'configuration.dart';
import 'match.dart';
import 'path_utils.dart';
import 'router.dart';
import 'state.dart';
/// The page builder for [GoRoute].
typedef GoRouterPageBuilder = Page<dynamic> Function(
BuildContext context,
GoRouterState state,
);
/// The widget builder for [GoRoute].
typedef GoRouterWidgetBuilder = Widget Function(
BuildContext context,
GoRouterState state,
);
/// The widget builder for [ShellRoute].
typedef ShellRouteBuilder = Widget Function(
BuildContext context,
GoRouterState state,
Widget child,
);
/// The page builder for [ShellRoute].
typedef ShellRoutePageBuilder = Page<dynamic> Function(
BuildContext context,
GoRouterState state,
Widget child,
);
/// The widget builder for [StatefulShellRoute].
typedef StatefulShellRouteBuilder = Widget Function(
BuildContext context,
GoRouterState state,
StatefulNavigationShell navigationShell,
);
/// The page builder for [StatefulShellRoute].
typedef StatefulShellRoutePageBuilder = Page<dynamic> Function(
BuildContext context,
GoRouterState state,
StatefulNavigationShell navigationShell,
);
/// Signature for functions used to build Navigators
typedef NavigatorBuilder = Widget Function(
List<NavigatorObserver>? observers, String? restorationScopeId);
/// Signature for function used in [RouteBase.onExit].
///
/// If the return value is true or the future resolve to true, the route will
/// exit as usual. Otherwise, the operation will abort.
typedef ExitCallback = FutureOr<bool> Function(
BuildContext context, GoRouterState state);
/// The base class for [GoRoute] and [ShellRoute].
///
/// Routes are defined in a tree such that parent routes must match the
/// current location for their child route to be considered a match. For
/// example the location "/home/user/12" matches with parent route "/home" and
/// child route "user/:userId".
///
/// To create sub-routes for a route, provide them as a [GoRoute] list
/// with the sub routes.
///
/// For example these routes:
/// ```
/// / => HomePage()
/// family/f1 => FamilyPage('f1')
/// person/p2 => PersonPage('f1', 'p2') ← showing this page, Back pops ↑
/// ```
///
/// Can be represented as:
///
/// ```
/// final GoRouter _router = GoRouter(
/// routes: <GoRoute>[
/// GoRoute(
/// path: '/',
/// pageBuilder: (BuildContext context, GoRouterState state) => MaterialPage<void>(
/// key: state.pageKey,
/// child: HomePage(families: Families.data),
/// ),
/// routes: <GoRoute>[
/// GoRoute(
/// path: 'family/:fid',
/// pageBuilder: (BuildContext context, GoRouterState state) {
/// final Family family = Families.family(state.pathParameters['fid']!);
/// return MaterialPage<void>(
/// key: state.pageKey,
/// child: FamilyPage(family: family),
/// );
/// },
/// routes: <GoRoute>[
/// GoRoute(
/// path: 'person/:pid',
/// pageBuilder: (BuildContext context, GoRouterState state) {
/// final Family family = Families.family(state.pathParameters['fid']!);
/// final Person person = family.person(state.pathParameters['pid']!);
/// return MaterialPage<void>(
/// key: state.pageKey,
/// child: PersonPage(family: family, person: person),
/// );
/// },
/// ),
/// ],
/// ),
/// ],
/// ),
/// ],
/// );
///
/// If there are multiple routes that match the location, the first match is used.
/// To make predefined routes to take precedence over dynamic routes eg. '/:id'
/// consider adding the dynamic route at the end of the routes
/// For example:
/// ```
/// final GoRouter _router = GoRouter(
/// routes: <GoRoute>[
/// GoRoute(
/// path: '/',
/// redirect: (_) => '/family/${Families.data[0].id}',
/// ),
/// GoRoute(
/// path: '/family',
/// pageBuilder: (BuildContext context, GoRouterState state) => ...,
/// ),
/// GoRoute(
/// path: '/:username',
/// pageBuilder: (BuildContext context, GoRouterState state) => ...,
/// ),
/// ],
/// );
/// ```
/// In the above example, if /family route is matched, it will be used.
/// else /:username route will be used.
/// ///
/// See [main.dart](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/main.dart)
@immutable
abstract class RouteBase with Diagnosticable {
const RouteBase._({
this.redirect,
required this.routes,
required this.parentNavigatorKey,
});
/// An optional redirect function for this route.
///
/// In the case that you like to make a redirection decision for a specific
/// route (or sub-route), consider doing so by passing a redirect function to
/// the GoRoute constructor.
///
/// For example:
/// ```
/// final GoRouter _router = GoRouter(
/// routes: <GoRoute>[
/// GoRoute(
/// path: '/',
/// redirect: (_) => '/family/${Families.data[0].id}',
/// ),
/// GoRoute(
/// path: '/family/:fid',
/// pageBuilder: (BuildContext context, GoRouterState state) => ...,
/// ),
/// ],
/// );
/// ```
///
/// If there are multiple redirects in the matched routes, the parent route's
/// redirect takes priority over sub-route's.
///
/// For example:
/// ```
/// final GoRouter _router = GoRouter(
/// routes: <GoRoute>[
/// GoRoute(
/// path: '/',
/// redirect: (_) => '/page1', // this takes priority over the sub-route.
/// routes: <GoRoute>[
/// GoRoute(
/// path: 'child',
/// redirect: (_) => '/page2',
/// ),
/// ],
/// ),
/// ],
/// );
/// ```
///
/// The `context.go('/child')` will be redirected to `/page1` instead of
/// `/page2`.
///
/// Redirect can also be used for conditionally preventing users from visiting
/// routes, also known as route guards. One canonical example is user
/// authentication. See [Redirection](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/redirection.dart)
/// for a complete runnable example.
///
/// If [BuildContext.dependOnInheritedWidgetOfExactType] is used during the
/// redirection (which is how `of` method is usually implemented), a
/// re-evaluation will be triggered if the [InheritedWidget] changes.
final GoRouterRedirect? redirect;
/// The list of child routes associated with this route.
final List<RouteBase> routes;
/// An optional key specifying which Navigator to display this route's screen
/// onto.
///
/// Specifying the root Navigator will stack this route onto that
/// Navigator instead of the nearest ShellRoute ancestor.
final GlobalKey<NavigatorState>? parentNavigatorKey;
/// Builds a lists containing the provided routes along with all their
/// descendant [routes].
static Iterable<RouteBase> routesRecursively(Iterable<RouteBase> routes) {
return routes.expand(
(RouteBase e) => <RouteBase>[e, ...routesRecursively(e.routes)]);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
if (parentNavigatorKey != null) {
properties.add(DiagnosticsProperty<GlobalKey<NavigatorState>>(
'parentNavKey', parentNavigatorKey));
}
}
}
/// A route that is displayed visually above the matching parent route using the
/// [Navigator].
///
/// The widget returned by [builder] is wrapped in [Page] and provided to the
/// root Navigator, the nearest ShellRoute ancestor's Navigator, or the
/// Navigator with a matching [parentNavigatorKey].
///
/// The Page depends on the application type: [MaterialPage] for
/// [MaterialApp], [CupertinoPage] for [CupertinoApp], or
/// [NoTransitionPage] for [WidgetsApp].
///
/// {@category Get started}
/// {@category Configuration}
/// {@category Transition animations}
/// {@category Named routes}
/// {@category Redirection}
class GoRoute extends RouteBase {
/// Constructs a [GoRoute].
/// - [path] and [name] cannot be empty strings.
/// - One of either [builder] or [pageBuilder] must be provided.
GoRoute({
required this.path,
this.name,
this.builder,
this.pageBuilder,
super.parentNavigatorKey,
super.redirect,
this.onExit,
super.routes = const <RouteBase>[],
}) : assert(path.isNotEmpty, 'GoRoute path cannot be empty'),
assert(name == null || name.isNotEmpty, 'GoRoute name cannot be empty'),
assert(pageBuilder != null || builder != null || redirect != null,
'builder, pageBuilder, or redirect must be provided'),
assert(onExit == null || pageBuilder != null || builder != null,
'if onExit is provided, one of pageBuilder or builder must be provided'),
super._() {
// cache the path regexp and parameters
_pathRE = patternToRegExp(path, pathParameters);
}
/// Whether this [GoRoute] only redirects to another route.
///
/// If this is true, this route must redirect location other than itself.
bool get redirectOnly => pageBuilder == null && builder == null;
/// Optional name of the route.
///
/// If used, a unique string name must be provided and it can not be empty.
///
/// This is used in [GoRouter.namedLocation] and its related API. This
/// property can be used to navigate to this route without knowing exact the
/// URI of it.
///
/// {@tool snippet}
/// Typical usage is as follows:
///
/// ```dart
/// GoRoute(
/// name: 'home',
/// path: '/',
/// builder: (BuildContext context, GoRouterState state) =>
/// HomeScreen(),
/// routes: <GoRoute>[
/// GoRoute(
/// name: 'family',
/// path: 'family/:fid',
/// builder: (BuildContext context, GoRouterState state) =>
/// FamilyScreen(),
/// ),
/// ],
/// );
///
/// context.go(
/// context.namedLocation('family'),
/// pathParameters: <String, String>{'fid': 123},
/// queryParameters: <String, String>{'qid': 'quid'},
/// );
/// ```
/// {@end-tool}
///
/// See the [named routes example](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/named_routes.dart)
/// for a complete runnable app.
final String? name;
/// The path of this go route.
///
/// For example:
/// ```
/// GoRoute(
/// path: '/',
/// pageBuilder: (BuildContext context, GoRouterState state) => MaterialPage<void>(
/// key: state.pageKey,
/// child: HomePage(families: Families.data),
/// ),
/// ),
/// ```
///
/// The path also support path parameters. For a path: `/family/:fid`, it
/// matches all URIs start with `/family/...`, e.g. `/family/123`,
/// `/family/456` and etc. The parameter values are stored in [GoRouterState]
/// that are passed into [pageBuilder] and [builder].
///
/// The query parameter are also capture during the route parsing and stored
/// in [GoRouterState].
///
/// See [Query parameters and path parameters](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/path_and_query_parameters.dart)
/// to learn more about parameters.
final String path;
/// A page builder for this route.
///
/// Typically a MaterialPage, as in:
/// ```
/// GoRoute(
/// path: '/',
/// pageBuilder: (BuildContext context, GoRouterState state) => MaterialPage<void>(
/// key: state.pageKey,
/// child: HomePage(families: Families.data),
/// ),
/// ),
/// ```
///
/// You can also use CupertinoPage, and for a custom page builder to use
/// custom page transitions, you can use [CustomTransitionPage].
final GoRouterPageBuilder? pageBuilder;
/// A custom builder for this route.
///
/// For example:
/// ```
/// GoRoute(
/// path: '/',
/// builder: (BuildContext context, GoRouterState state) => FamilyPage(
/// families: Families.family(
/// state.pathParameters['id'],
/// ),
/// ),
/// ),
/// ```
///
final GoRouterWidgetBuilder? builder;
/// Called when this route is removed from GoRouter's route history.
///
/// Some example this callback may be called:
/// * This route is removed as the result of [GoRouter.pop].
/// * This route is no longer in the route history after a [GoRouter.go].
///
/// This method can be useful it one wants to launch a dialog for user to
/// confirm if they want to exit the screen.
///
/// ```
/// final GoRouter _router = GoRouter(
/// routes: <GoRoute>[
/// GoRoute(
/// path: '/',
/// onExit: (BuildContext context) => showDialog<bool>(
/// context: context,
/// builder: (BuildContext context) {
/// return AlertDialog(
/// title: const Text('Do you want to exit this page?'),
/// actions: <Widget>[
/// TextButton(
/// style: TextButton.styleFrom(
/// textStyle: Theme.of(context).textTheme.labelLarge,
/// ),
/// child: const Text('Go Back'),
/// onPressed: () {
/// Navigator.of(context).pop(false);
/// },
/// ),
/// TextButton(
/// style: TextButton.styleFrom(
/// textStyle: Theme.of(context).textTheme.labelLarge,
/// ),
/// child: const Text('Confirm'),
/// onPressed: () {
/// Navigator.of(context).pop(true);
/// },
/// ),
/// ],
/// );
/// },
/// ),
/// ),
/// ],
/// );
/// ```
final ExitCallback? onExit;
// TODO(chunhtai): move all regex related help methods to path_utils.dart.
/// Match this route against a location.
RegExpMatch? matchPatternAsPrefix(String loc) =>
_pathRE.matchAsPrefix(loc) as RegExpMatch?;
/// Extract the path parameters from a match.
Map<String, String> extractPathParams(RegExpMatch match) =>
extractPathParameters(pathParameters, match);
/// The path parameters in this route.
@internal
final List<String> pathParameters = <String>[];
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(StringProperty('name', name));
properties.add(StringProperty('path', path));
properties.add(
FlagProperty('redirect', value: redirectOnly, ifTrue: 'Redirect Only'));
}
late final RegExp _pathRE;
}
/// Base class for classes that act as shells for sub-routes, such
/// as [ShellRoute] and [StatefulShellRoute].
abstract class ShellRouteBase extends RouteBase {
/// Constructs a [ShellRouteBase].
const ShellRouteBase._({
super.redirect,
required super.routes,
required super.parentNavigatorKey,
}) : super._();
static void _debugCheckSubRouteParentNavigatorKeys(
List<RouteBase> subRoutes, GlobalKey<NavigatorState> navigatorKey) {
for (final RouteBase route in subRoutes) {
assert(
route.parentNavigatorKey == null ||
route.parentNavigatorKey == navigatorKey,
"sub-route's parent navigator key must either be null or has the same navigator key as parent's key");
if (route is GoRoute && route.redirectOnly) {
// This route does not produce a page, need to check its sub-routes
// instead.
_debugCheckSubRouteParentNavigatorKeys(route.routes, navigatorKey);
}
}
}
/// Attempts to build the Widget representing this shell route.
///
/// Returns null if this shell route does not build a Widget, but instead uses
/// a Page to represent itself (see [buildPage]).
Widget? buildWidget(BuildContext context, GoRouterState state,
ShellRouteContext shellRouteContext);
/// Attempts to build the Page representing this shell route.
///
/// Returns null if this shell route does not build a Page, but instead uses
/// a Widget to represent itself (see [buildWidget]).
Page<dynamic>? buildPage(BuildContext context, GoRouterState state,
ShellRouteContext shellRouteContext);
/// Returns the key for the [Navigator] that is to be used for the specified
/// immediate sub-route of this shell route.
GlobalKey<NavigatorState> navigatorKeyForSubRoute(RouteBase subRoute);
}
/// Context object used when building the shell and Navigator for a shell route.
class ShellRouteContext {
/// Constructs a [ShellRouteContext].
ShellRouteContext({
required this.route,
required this.routerState,
required this.navigatorKey,
required this.routeMatchList,
required this.navigatorBuilder,
});
/// The associated shell route.
final ShellRouteBase route;
/// The current route state associated with [route].
final GoRouterState routerState;
/// The [Navigator] key to be used for the nested navigation associated with
/// [route].
final GlobalKey<NavigatorState> navigatorKey;
/// The route match list representing the current location within the
/// associated shell route.
final RouteMatchList routeMatchList;
/// Function used to build the [Navigator] for the current route.
final NavigatorBuilder navigatorBuilder;
}
/// A route that displays a UI shell around the matching child route.
///
/// When a ShellRoute is added to the list of routes on GoRouter or GoRoute, a
/// new Navigator is used to display any matching sub-routes instead of placing
/// them on the root Navigator.
///
/// To display a child route on a different Navigator, provide it with a
/// [parentNavigatorKey] that matches the key provided to either the [GoRouter]
/// or [ShellRoute] constructor. In this example, the _rootNavigator key is
/// passed to the /b/details route so that it displays on the root Navigator
/// instead of the ShellRoute's Navigator:
///
/// ```
/// final GlobalKey<NavigatorState> _rootNavigatorKey =
/// GlobalKey<NavigatorState>();
///
/// final GoRouter _router = GoRouter(
/// navigatorKey: _rootNavigatorKey,
/// initialLocation: '/a',
/// routes: [
/// ShellRoute(
/// navigatorKey: _shellNavigatorKey,
/// builder: (context, state, child) {
/// return ScaffoldWithNavBar(child: child);
/// },
/// routes: [
/// // This screen is displayed on the ShellRoute's Navigator.
/// GoRoute(
/// path: '/a',
/// builder: (context, state) {
/// return const ScreenA();
/// },
/// routes: <RouteBase>[
/// // This screen is displayed on the ShellRoute's Navigator.
/// GoRoute(
/// path: 'details',
/// builder: (BuildContext context, GoRouterState state) {
/// return const DetailsScreen(label: 'A');
/// },
/// ),
/// ],
/// ),
/// // Displayed ShellRoute's Navigator.
/// GoRoute(
/// path: '/b',
/// builder: (BuildContext context, GoRouterState state) {
/// return const ScreenB();
/// },
/// routes: <RouteBase>[
/// // Displayed on the root Navigator by specifying the
/// // [parentNavigatorKey].
/// GoRoute(
/// path: 'details',
/// parentNavigatorKey: _rootNavigatorKey,
/// builder: (BuildContext context, GoRouterState state) {
/// return const DetailsScreen(label: 'B');
/// },
/// ),
/// ],
/// ),
/// ],
/// ),
/// ],
/// );
/// ```
///
/// The widget built by the matching sub-route becomes the child parameter
/// of the [builder].
///
/// For example:
///
/// ```
/// ShellRoute(
/// builder: (BuildContext context, GoRouterState state, Widget child) {
/// return Scaffold(
/// appBar: AppBar(
/// title: Text('App Shell')
/// ),
/// body: Center(
/// child: child,
/// ),
/// );
/// },
/// routes: [
/// GoRoute(
/// path: 'a'
/// builder: (BuildContext context, GoRouterState state) {
/// return Text('Child Route "/a"');
/// }
/// ),
/// ],
/// ),
/// ```
///
/// {@category Configuration}
class ShellRoute extends ShellRouteBase {
/// Constructs a [ShellRoute].
ShellRoute({
super.redirect,
this.builder,
this.pageBuilder,
this.observers,
required super.routes,
super.parentNavigatorKey,
GlobalKey<NavigatorState>? navigatorKey,
this.restorationScopeId,
}) : assert(routes.isNotEmpty),
navigatorKey = navigatorKey ?? GlobalKey<NavigatorState>(),
super._() {
assert(() {
ShellRouteBase._debugCheckSubRouteParentNavigatorKeys(
routes, this.navigatorKey);
return true;
}());
}
/// The widget builder for a shell route.
///
/// Similar to [GoRoute.builder], but with an additional child parameter. This
/// child parameter is the Widget managing the nested navigation for the
/// matching sub-routes. Typically, a shell route builds its shell around this
/// Widget.
final ShellRouteBuilder? builder;
/// The page builder for a shell route.
///
/// Similar to [GoRoute.pageBuilder], but with an additional child parameter.
/// This child parameter is the Widget managing the nested navigation for the
/// matching sub-routes. Typically, a shell route builds its shell around this
/// Widget.
final ShellRoutePageBuilder? pageBuilder;
@override
Widget? buildWidget(BuildContext context, GoRouterState state,
ShellRouteContext shellRouteContext) {
if (builder != null) {
final Widget navigator =
shellRouteContext.navigatorBuilder(observers, restorationScopeId);
return builder!(context, state, navigator);
}
return null;
}
@override
Page<dynamic>? buildPage(BuildContext context, GoRouterState state,
ShellRouteContext shellRouteContext) {
if (pageBuilder != null) {
final Widget navigator =
shellRouteContext.navigatorBuilder(observers, restorationScopeId);
return pageBuilder!(context, state, navigator);
}
return null;
}
/// The observers for a shell route.
///
/// The observers parameter is used by the [Navigator] built for this route.
/// sub-route's observers.
final List<NavigatorObserver>? observers;
/// The [GlobalKey] to be used by the [Navigator] built for this route.
/// All ShellRoutes build a Navigator by default. Child GoRoutes
/// are placed onto this Navigator instead of the root Navigator.
final GlobalKey<NavigatorState> navigatorKey;
/// Restoration ID to save and restore the state of the navigator, including
/// its history.
final String? restorationScopeId;
@override
GlobalKey<NavigatorState> navigatorKeyForSubRoute(RouteBase subRoute) {
assert(routes.contains(subRoute));
return navigatorKey;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<GlobalKey<NavigatorState>>(
'navigatorKey', navigatorKey));
}
}
/// A route that displays a UI shell with separate [Navigator]s for its
/// sub-routes.
///
/// Similar to [ShellRoute], this route class places its sub-route on a
/// different Navigator than the root [Navigator]. However, this route class
/// differs in that it creates separate [Navigator]s for each of its nested
/// branches (i.e. parallel navigation trees), making it possible to build an
/// app with stateful nested navigation. This is convenient when for instance
/// implementing a UI with a [BottomNavigationBar], with a persistent navigation
/// state for each tab.
///
/// A StatefulShellRoute is created by specifying a List of
/// [StatefulShellBranch] items, each representing a separate stateful branch
/// in the route tree. StatefulShellBranch provides the root routes and the
/// Navigator key ([GlobalKey]) for the branch, as well as an optional initial
/// location.
///
/// Like [ShellRoute], either a [builder] or a [pageBuilder] must be provided
/// when creating a StatefulShellRoute. However, these builders differ slightly
/// in that they accept a [StatefulNavigationShell] parameter instead of a
/// child Widget. The StatefulNavigationShell can be used to access information
/// about the state of the route, as well as to switch the active branch (i.e.
/// restoring the navigation stack of another branch). The latter is
/// accomplished by using the method [StatefulNavigationShell.goBranch], for
/// example:
///
/// ```
/// void _onItemTapped(int index) {
/// navigationShell.goBranch(index: index);
/// }
/// ```
///
/// The StatefulNavigationShell is also responsible for managing and maintaining
/// the state of the branch Navigators. Typically, a shell is built around this
/// Widget, for example by using it as the body of [Scaffold] with a
/// [BottomNavigationBar].
///
/// When creating a StatefulShellRoute, a [navigatorContainerBuilder] function
/// must be provided. This function is responsible for building the actual
/// container for the Widgets representing the branch Navigators. Typically,
/// the Widget returned by this function handles the layout (including
/// [Offstage] handling etc) of the branch Navigators and any animations needed
/// when switching active branch.
///
/// For a default implementation of [navigatorContainerBuilder] that is
/// appropriate for most use cases, consider using the constructor
/// [StatefulShellRoute.indexedStack].
///
/// With StatefulShellRoute (and any route below it), animated transitions
/// between routes in the same navigation stack works the same way as with other
/// route classes, and can be customized using pageBuilder. However, since
/// StatefulShellRoute maintains a set of parallel navigation stacks,
/// any transitions when switching between branches is the responsibility of the
/// branch Navigator container (i.e. [navigatorContainerBuilder]). The default
/// [IndexedStack] implementation ([StatefulShellRoute.indexedStack]) does not
/// use animated transitions, but an example is provided on how to accomplish
/// this (see link to custom StatefulShellRoute example below).
///
/// See also:
/// * [StatefulShellRoute.indexedStack] which provides a default
/// StatefulShellRoute implementation suitable for most use cases.
/// * [Stateful Nested Navigation example](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/stateful_shell_route.dart)
/// for a complete runnable example using StatefulShellRoute.
/// * [Custom StatefulShellRoute example](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/others/custom_stateful_shell_route.dart)
/// which demonstrates how to customize the container for the branch Navigators
/// and how to implement animated transitions when switching branches.
class StatefulShellRoute extends ShellRouteBase {
/// Constructs a [StatefulShellRoute] from a list of [StatefulShellBranch]es,
/// each representing a separate nested navigation tree (branch).
///
/// A separate [Navigator] will be created for each of the branches, using
/// the navigator key specified in [StatefulShellBranch]. The Widget
/// implementing the container for the branch Navigators is provided by
/// [navigatorContainerBuilder].
StatefulShellRoute({
required this.branches,
super.redirect,
this.builder,
this.pageBuilder,
required this.navigatorContainerBuilder,
super.parentNavigatorKey,
this.restorationScopeId,
}) : assert(branches.isNotEmpty),
assert((pageBuilder != null) || (builder != null),
'One of builder or pageBuilder must be provided'),
assert(_debugUniqueNavigatorKeys(branches).length == branches.length,
'Navigator keys must be unique'),
assert(_debugValidateParentNavigatorKeys(branches)),
assert(_debugValidateRestorationScopeIds(restorationScopeId, branches)),
super._(routes: _routes(branches));
/// Constructs a StatefulShellRoute that uses an [IndexedStack] for its
/// nested [Navigator]s.
///
/// This constructor provides an IndexedStack based implementation for the
/// container ([navigatorContainerBuilder]) used to manage the Widgets
/// representing the branch Navigators. Apart from that, this constructor
/// works the same way as the default constructor.
///
/// See [Stateful Nested Navigation](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/stacked_shell_route.dart)
/// for a complete runnable example using StatefulShellRoute.indexedStack.
StatefulShellRoute.indexedStack({
required List<StatefulShellBranch> branches,
GoRouterRedirect? redirect,
StatefulShellRouteBuilder? builder,
GlobalKey<NavigatorState>? parentNavigatorKey,
StatefulShellRoutePageBuilder? pageBuilder,
String? restorationScopeId,
}) : this(
branches: branches,
redirect: redirect,
builder: builder,
pageBuilder: pageBuilder,
parentNavigatorKey: parentNavigatorKey,
restorationScopeId: restorationScopeId,
navigatorContainerBuilder: _indexedStackContainerBuilder,
);
/// Restoration ID to save and restore the state of the navigator, including
/// its history.
final String? restorationScopeId;
/// The widget builder for a stateful shell route.
///
/// Similar to [GoRoute.builder], but with an additional
/// [StatefulNavigationShell] parameter. StatefulNavigationShell is a Widget
/// responsible for managing the nested navigation for the
/// matching sub-routes. Typically, a shell route builds its shell around this
/// Widget. StatefulNavigationShell can also be used to access information
/// about which branch is active, and also to navigate to a different branch
/// (using [StatefulNavigationShell.goBranch]).
///
/// Custom implementations may choose to ignore the child parameter passed to
/// the builder function, and instead use [StatefulNavigationShell] to
/// create a custom container for the branch Navigators.
final StatefulShellRouteBuilder? builder;
/// The page builder for a stateful shell route.
///
/// Similar to [GoRoute.pageBuilder], but with an additional
/// [StatefulNavigationShell] parameter. StatefulNavigationShell is a Widget
/// responsible for managing the nested navigation for the
/// matching sub-routes. Typically, a shell route builds its shell around this
/// Widget. StatefulNavigationShell can also be used to access information
/// about which branch is active, and also to navigate to a different branch
/// (using [StatefulNavigationShell.goBranch]).
///
/// Custom implementations may choose to ignore the child parameter passed to
/// the builder function, and instead use [StatefulNavigationShell] to
/// create a custom container for the branch Navigators.
final StatefulShellRoutePageBuilder? pageBuilder;
/// The builder for the branch Navigator container.
///
/// The function responsible for building the container for the branch
/// Navigators. When this function is invoked, access is provided to a List of
/// Widgets representing the branch Navigators, where the the index
/// corresponds to the index of in [branches].
///
/// The builder function is expected to return a Widget that ensures that the
/// state of the branch Widgets is maintained, for instance by inducting them
/// in the Widget tree.
final ShellNavigationContainerBuilder navigatorContainerBuilder;
/// Representations of the different stateful route branches that this
/// shell route will manage.
///
/// Each branch uses a separate [Navigator], identified
/// [StatefulShellBranch.navigatorKey].
final List<StatefulShellBranch> branches;
final GlobalKey<StatefulNavigationShellState> _shellStateKey =
GlobalKey<StatefulNavigationShellState>();
@override
Widget? buildWidget(BuildContext context, GoRouterState state,
ShellRouteContext shellRouteContext) {
if (builder != null) {
return builder!(context, state, _createShell(context, shellRouteContext));
}
return null;
}
@override
Page<dynamic>? buildPage(BuildContext context, GoRouterState state,
ShellRouteContext shellRouteContext) {
if (pageBuilder != null) {
return pageBuilder!(
context, state, _createShell(context, shellRouteContext));
}
return null;
}
@override
GlobalKey<NavigatorState> navigatorKeyForSubRoute(RouteBase subRoute) {
final StatefulShellBranch? branch = branches.firstWhereOrNull(
(StatefulShellBranch e) => e.routes.contains(subRoute));
assert(branch != null);
return branch!.navigatorKey;
}
Iterable<GlobalKey<NavigatorState>> get _navigatorKeys =>
branches.map((StatefulShellBranch b) => b.navigatorKey);
StatefulNavigationShell _createShell(
BuildContext context, ShellRouteContext shellRouteContext) =>
StatefulNavigationShell(
shellRouteContext: shellRouteContext,
router: GoRouter.of(context),
containerBuilder: navigatorContainerBuilder);
static Widget _indexedStackContainerBuilder(BuildContext context,
StatefulNavigationShell navigationShell, List<Widget> children) {
return _IndexedStackedRouteBranchContainer(
currentIndex: navigationShell.currentIndex, children: children);
}
static List<RouteBase> _routes(List<StatefulShellBranch> branches) =>
branches.expand((StatefulShellBranch e) => e.routes).toList();
static Set<GlobalKey<NavigatorState>> _debugUniqueNavigatorKeys(
List<StatefulShellBranch> branches) =>
Set<GlobalKey<NavigatorState>>.from(
branches.map((StatefulShellBranch e) => e.navigatorKey));
static bool _debugValidateParentNavigatorKeys(
List<StatefulShellBranch> branches) {
for (final StatefulShellBranch branch in branches) {
for (final RouteBase route in branch.routes) {
if (route is GoRoute) {
assert(route.parentNavigatorKey == null ||
route.parentNavigatorKey == branch.navigatorKey);
}
}
}
return true;
}
static bool _debugValidateRestorationScopeIds(
String? restorationScopeId, List<StatefulShellBranch> branches) {
if (branches
.map((StatefulShellBranch e) => e.restorationScopeId)
.whereNotNull()
.isNotEmpty) {
assert(
restorationScopeId != null,
'A restorationScopeId must be set for '
'the StatefulShellRoute when using restorationScopeIds on one or more '
'of the branches');
}
return true;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Iterable<GlobalKey<NavigatorState>>>(
'navigatorKeys', _navigatorKeys));
}
}
/// Representation of a separate branch in a stateful navigation tree, used to
/// configure [StatefulShellRoute].
///
/// The only required argument when creating a StatefulShellBranch is the
/// sub-routes ([routes]), however sometimes it may be convenient to also
/// provide a [initialLocation]. The value of this parameter is used when
/// loading the branch for the first time (for instance when switching branch
/// using the goBranch method in [StatefulNavigationShell]).
///
/// A separate [Navigator] will be built for each StatefulShellBranch in a
/// [StatefulShellRoute], and the routes of this branch will be placed onto that
/// Navigator instead of the root Navigator. A custom [navigatorKey] can be
/// provided when creating a StatefulShellBranch, which can be useful when the
/// Navigator needs to be accessed elsewhere. If no key is provided, a default
/// one will be created.
@immutable
class StatefulShellBranch {
/// Constructs a [StatefulShellBranch].
StatefulShellBranch({
required this.routes,
GlobalKey<NavigatorState>? navigatorKey,
this.initialLocation,
this.restorationScopeId,
this.observers,
}) : navigatorKey = navigatorKey ?? GlobalKey<NavigatorState>() {
assert(() {