Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[go_router] Add support for preloading branches of StatefulShellRoute (revised solution) #6467

Merged
merged 20 commits into from
Nov 12, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/go_router/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 13.3.0

- Adds preload support to StatefulShellRoute, configurable via `preload` parameter on StatefulShellBranch.

## 13.2.2

- Fixes restoreRouteInformation issue when GoRouter.optionURLReflectsImperativeAPIs is true and the last match is ShellRouteMatch
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ final GlobalKey<NavigatorState> _rootNavigatorKey =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> _tabANavigatorKey =
GlobalKey<NavigatorState>(debugLabel: 'tabANav');
final GlobalKey<NavigatorState> _tabBNavigatorKey =
GlobalKey<NavigatorState>(debugLabel: 'tabBNav');
final GlobalKey<NavigatorState> _tabB1NavigatorKey =
GlobalKey<NavigatorState>(debugLabel: 'tabB1Nav');
final GlobalKey<NavigatorState> _tabB2NavigatorKey =
GlobalKey<NavigatorState>(debugLabel: 'tabB2Nav');

// This example demonstrates how to setup nested navigation using a
// BottomNavigationBar, where each bar item uses its own persistent navigator,
Expand Down Expand Up @@ -80,71 +86,69 @@ class NestedTabNavigationExampleApp extends StatelessWidget {

// The route branch for the third tab of the bottom navigation bar.
StatefulShellBranch(
navigatorKey: _tabBNavigatorKey,
// To enable preloading of the initial locations of branches, pass
// 'true' for the parameter preload.
preload: true,
// StatefulShellBranch will automatically use the first descendant
// GoRoute as the initial location of the branch. If another route
// is desired, specify the location of it using the defaultLocation
// parameter.
// defaultLocation: '/c2',
// defaultLocation: '/b1',
routes: <RouteBase>[
StatefulShellRoute(
StatefulShellRoute.indexedStack(
tolo marked this conversation as resolved.
Show resolved Hide resolved
builder: (BuildContext context, GoRouterState state,
StatefulNavigationShell navigationShell) {
// Just like with the top level StatefulShellRoute, no
// customization is done in the builder function.
return navigationShell;
return TabbedRootScreen(navigationShell: navigationShell);
},
navigatorContainerBuilder: (BuildContext context,
StatefulNavigationShell navigationShell,
List<Widget> children) {
// Returning a customized container for the branch
// Navigators (i.e. the `List<Widget> children` argument).
//
// See TabbedRootScreen for more details on how the children
// are managed (in a TabBarView).
return TabbedRootScreen(
navigationShell: navigationShell, children: children);
},
// This bottom tab uses a nested shell, wrapping sub routes in a
// top TabBar.
branches: <StatefulShellBranch>[
StatefulShellBranch(routes: <GoRoute>[
GoRoute(
path: '/b1',
builder: (BuildContext context, GoRouterState state) =>
const TabScreen(
label: 'B1', detailsPath: '/b1/details'),
routes: <RouteBase>[
StatefulShellBranch(
navigatorKey: _tabB1NavigatorKey,
routes: <GoRoute>[
GoRoute(
path: 'details',
path: '/b1',
builder:
(BuildContext context, GoRouterState state) =>
const DetailsScreen(
label: 'B1',
withScaffold: false,
),
const TabScreen(
label: 'B1', detailsPath: '/b1/details'),
routes: <RouteBase>[
GoRoute(
path: 'details',
builder:
(BuildContext context, GoRouterState state) =>
const DetailsScreen(
label: 'B1',
withScaffold: false,
),
),
],
),
],
),
]),
StatefulShellBranch(routes: <GoRoute>[
GoRoute(
path: '/b2',
builder: (BuildContext context, GoRouterState state) =>
const TabScreen(
label: 'B2', detailsPath: '/b2/details'),
routes: <RouteBase>[
]),
StatefulShellBranch(
navigatorKey: _tabB2NavigatorKey,
// To enable preloading for all nested branches, set
// preload to 'true'.
preload: true,
routes: <GoRoute>[
GoRoute(
path: 'details',
path: '/b2',
builder:
(BuildContext context, GoRouterState state) =>
const DetailsScreen(
label: 'B2',
withScaffold: false,
),
const TabScreen(
label: 'B2', detailsPath: '/b2/details'),
routes: <RouteBase>[
GoRoute(
path: 'details',
builder:
(BuildContext context, GoRouterState state) =>
const DetailsScreen(
label: 'B2',
withScaffold: false,
),
),
],
),
],
),
]),
]),
],
),
],
Expand Down Expand Up @@ -376,23 +380,20 @@ class DetailsScreenState extends State<DetailsScreen> {
/// Builds a nested shell using a [TabBar] and [TabBarView].
class TabbedRootScreen extends StatefulWidget {
/// Constructs a TabbedRootScreen
const TabbedRootScreen(
{required this.navigationShell, required this.children, super.key});
const TabbedRootScreen({required this.navigationShell, super.key});

/// The current state of the parent StatefulShellRoute.
final StatefulNavigationShell navigationShell;

/// The children (branch Navigators) to display in the [TabBarView].
final List<Widget> children;

@override
State<StatefulWidget> createState() => _TabbedRootScreenState();
}

class _TabbedRootScreenState extends State<TabbedRootScreen>
with SingleTickerProviderStateMixin {
late final int branchCount = widget.navigationShell.route.branches.length;
late final TabController _tabController = TabController(
length: widget.children.length,
length: branchCount,
vsync: this,
initialIndex: widget.navigationShell.currentIndex);

Expand All @@ -404,9 +405,9 @@ class _TabbedRootScreenState extends State<TabbedRootScreen>

@override
Widget build(BuildContext context) {
final List<Tab> tabs = widget.children
.mapIndexed((int i, _) => Tab(text: 'Tab ${i + 1}'))
.toList();
final List<Tab> tabs =
List<Tab>.generate(branchCount, (int i) => Tab(text: 'Tab ${i + 1}'))
.toList();

return Scaffold(
appBar: AppBar(
Expand All @@ -416,10 +417,7 @@ class _TabbedRootScreenState extends State<TabbedRootScreen>
tabs: tabs,
onTap: (int tappedIndex) => _onTabTap(context, tappedIndex),
)),
body: TabBarView(
controller: _tabController,
children: widget.children,
),
body: widget.navigationShell,
);
}

Expand All @@ -441,6 +439,11 @@ class TabScreen extends StatelessWidget {

@override
Widget build(BuildContext context) {
/// If preloading is enabled on the top StatefulShellRoute, this will be
/// printed directly after the app has been started, but only for the route
/// that is the initial location ('/b1')
debugPrint('Building TabScreen - $label');

return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
Expand Down
3 changes: 3 additions & 0 deletions packages/go_router/example/lib/stateful_shell_route.dart
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ class NestedTabNavigationExampleApp extends StatelessWidget {
],
),
],
// To enable preloading of the initial locations of branches, pass
// 'true' for the parameter preload.
// preload: true,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd find it clearer if the last line was uncommented as preload: false

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You may be right, I'll consider this.

),

// The route branch for the second tab of the bottom navigation bar.
Expand Down
12 changes: 9 additions & 3 deletions packages/go_router/lib/src/builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -270,16 +270,22 @@ class _CustomNavigatorState extends State<_CustomNavigator> {
route: match.route,
routerState: state,
navigatorKey: navigatorKey,
match: match,
routeMatchList: widget.matchList,
navigatorBuilder:
(List<NavigatorObserver>? observers, String? restorationScopeId) {
navigatorBuilder: (
GlobalKey<NavigatorState> navigatorKey,
ShellRouteMatch match,
RouteMatchList matchList,
List<NavigatorObserver>? observers,
String? restorationScopeId,
) {
return _CustomNavigator(
// The state needs to persist across rebuild.
key: GlobalObjectKey(navigatorKey.hashCode),
navigatorRestorationId: restorationScopeId,
navigatorKey: navigatorKey,
matches: match.matches,
matchList: widget.matchList,
matchList: matchList,
configuration: widget.configuration,
observers: observers ?? const <NavigatorObserver>[],
onPopPageWithRouteMatch: widget.onPopPageWithRouteMatch,
Expand Down
85 changes: 78 additions & 7 deletions packages/go_router/lib/src/route.dart
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,13 @@ typedef StatefulShellRoutePageBuilder = Page<dynamic> Function(

/// Signature for functions used to build Navigators
typedef NavigatorBuilder = Widget Function(
List<NavigatorObserver>? observers, String? restorationScopeId);
GlobalKey<NavigatorState> navigatorKey,
ShellRouteMatch match,
RouteMatchList matchList,
List<NavigatorObserver>? observers,
String? restorationScopeId);
// typedef NavigatorBuilder = Widget Function(
tolo marked this conversation as resolved.
Show resolved Hide resolved
// List<NavigatorObserver>? observers, String? restorationScopeId);

/// Signature for function used in [RouteBase.onExit].
///
Expand Down Expand Up @@ -502,6 +508,7 @@ class ShellRouteContext {
required this.route,
required this.routerState,
required this.navigatorKey,
required this.match,
required this.routeMatchList,
required this.navigatorBuilder,
});
Expand All @@ -516,12 +523,22 @@ class ShellRouteContext {
/// [route].
final GlobalKey<NavigatorState> navigatorKey;

/// The `ShellRouteMatch` in [routeMatchList] that corresponds to the
/// associated shell route.
final ShellRouteMatch match;

/// 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;

Widget _buildNavigatorForCurrentRoute(
List<NavigatorObserver>? observers, String? restorationScopeId) {
return navigatorBuilder(
navigatorKey, match, routeMatchList, observers, restorationScopeId);
}
}

/// A route that displays a UI shell around the matching child route.
Expand Down Expand Up @@ -659,8 +676,8 @@ class ShellRoute extends ShellRouteBase {
Widget? buildWidget(BuildContext context, GoRouterState state,
ShellRouteContext shellRouteContext) {
if (builder != null) {
final Widget navigator =
shellRouteContext.navigatorBuilder(observers, restorationScopeId);
final Widget navigator = shellRouteContext._buildNavigatorForCurrentRoute(
observers, restorationScopeId);
return builder!(context, state, navigator);
}
return null;
Expand All @@ -670,8 +687,8 @@ class ShellRoute extends ShellRouteBase {
Page<dynamic>? buildPage(BuildContext context, GoRouterState state,
ShellRouteContext shellRouteContext) {
if (pageBuilder != null) {
final Widget navigator =
shellRouteContext.navigatorBuilder(observers, restorationScopeId);
final Widget navigator = shellRouteContext._buildNavigatorForCurrentRoute(
observers, restorationScopeId);
return pageBuilder!(context, state, navigator);
}
return null;
Expand Down Expand Up @@ -988,6 +1005,7 @@ class StatefulShellBranch {
this.initialLocation,
this.restorationScopeId,
this.observers,
this.preload = false,
tolo marked this conversation as resolved.
Show resolved Hide resolved
}) : navigatorKey = navigatorKey ?? GlobalKey<NavigatorState>() {
assert(() {
ShellRouteBase._debugCheckSubRouteParentNavigatorKeys(
Expand Down Expand Up @@ -1024,6 +1042,22 @@ class StatefulShellBranch {
/// The observers parameter is used by the [Navigator] built for this branch.
final List<NavigatorObserver>? observers;

/// Whether this route branch should be loaded only when navigating to it for
tolo marked this conversation as resolved.
Show resolved Hide resolved
/// the first time (the default behavior, i.e. 'false'), or if it should be
/// eagerly loaded (preloaded).
///
/// If this property is true, the branch will be loaded immediately when the
/// associated [StatefulShellRoute] is visited for the first time. In that
/// case, the branch will be preloaded by navigating to the initial location
/// (see [initialLocation]).
///
/// *Note:* The primary purpose of branch preloading is to enhance the user
/// experience when switching branches, which might for instance involve
/// preparing the UI for animated transitions etc. Care must be taken to
/// **keep the preloading to an absolute minimum** to avoid any unnecessary
tolo marked this conversation as resolved.
Show resolved Hide resolved
/// resource use.
final bool preload;

/// The default route of this branch, i.e. the first descendant [GoRoute].
///
/// This route will be used when loading the branch for the first time, if
Expand Down Expand Up @@ -1172,6 +1206,9 @@ class StatefulNavigationShellState extends State<StatefulNavigationShell>
final Map<StatefulShellBranch, _RestorableRouteMatchList> _branchLocations =
<StatefulShellBranch, _RestorableRouteMatchList>{};

bool _isBranchLoaded(StatefulShellBranch branch) =>
_branchNavigators[branch.navigatorKey] != null;

@override
String? get restorationId => route.restorationScopeId;

Expand Down Expand Up @@ -1226,6 +1263,8 @@ class StatefulNavigationShellState extends State<StatefulNavigationShell>
}

void _updateCurrentBranchStateFromWidget() {
_preloadBranches();

final StatefulShellBranch branch = route.branches[widget.currentIndex];
final ShellRouteContext shellRouteContext = widget.shellRouteContext;
final RouteMatchList currentBranchLocation =
Expand All @@ -1242,8 +1281,40 @@ class StatefulNavigationShellState extends State<StatefulNavigationShell>
final bool locationChanged =
previousBranchLocation != currentBranchLocation;
if (locationChanged || !hasExistingNavigator) {
_branchNavigators[branch.navigatorKey] = shellRouteContext
.navigatorBuilder(branch.observers, branch.restorationScopeId);
_branchNavigators[branch.navigatorKey] =
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just realized somewhere in this method should probably remove entries in _branchNavigators the are no longer in the StatefulShellRoute?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, that is definitely necessary to do now. Will have a look at it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@chuntai, I added a fix for removing old entries, but when attempting to write a test case, I ran into issues with duplicate GlobalKeys (_shellStateKey) when updating the dynamic RoutingConfig. Or - I should be clear - at first the test case worked, but not because of the code I added, but instead because the entire StatefulShellRoute was replaced/reloaded. But when I added the possibility to set the GlobalKey<StatefulNavigationShellState> _shellStateKey to maintain state, I started to get this error.

When trying to troubleshoot it, I started to wonder whether dynamic RoutingConfig full supports ShellRoutes, at least with state. Added some test cases to test this, and it seems simple StatefulWidgets in a simple routing scenario works, but when adding a (regular) ShellRoute with a stateful shell I also get and issue with duplicate GlobalKeys.

Not sure if I just missed something, but I anyway added a gist with the test cases here: https://gist.github.com/tolo/922fd838cdea30b17121533b0012eda4

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you file an issue for it? looks like a bug

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is the fix in this pr already?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is now. 😊 Note though that I disabled two tests that fail due to the issue I mentioned above.

shellRouteContext._buildNavigatorForCurrentRoute(
branch.observers, branch.restorationScopeId);
}
}

void _preloadBranches() {
for (int i = 0; i < route.branches.length; i++) {
final StatefulShellBranch branch = route.branches[i];
if (i != widget.currentIndex &&
branch.preload &&
!_isBranchLoaded(branch)) {
final RouteMatchList matchList = _router.configuration
.findMatch(widget._effectiveInitialBranchLocation(i));

ShellRouteMatch? match;
matchList.visitRouteMatches((RouteMatchBase e) {
if (e is ShellRouteMatch && e.route == widget.route) {
match = e;
return false;
}
return true;
});

final Widget navigator = widget.shellRouteContext.navigatorBuilder(
tolo marked this conversation as resolved.
Show resolved Hide resolved
branch.navigatorKey,
match!,
matchList,
branch.observers,
branch.restorationScopeId);

_branchLocation(branch, false).value = matchList;
_branchNavigators[branch.navigatorKey] = navigator;
}
}
}

Expand Down
Loading