Skip to content

Commit 17e14c2

Browse files
authored
[go_router] Fix shell route key collisions and dynamic branch updates (flutter#12549)
This supersedes flutter/packages#11143, which was closed as inactive. It incorporates the review feedback from that PR. ## Problem When `push()` navigates between sibling or nested regular `ShellRoute` branches, multiple shell pages and navigators can coexist in the widget tree. This could produce duplicate page or widget keys because: - `_CustomNavigator` was keyed using `GlobalObjectKey(navigatorKey.hashCode)`, so distinct navigator keys with the same hash were treated as the same key. - `ShellRouteMatch.pageKey` was derived only from `route.hashCode`. - Re-entering a `ShellRoute` that was already present in the imperative stack reused its page and navigator identities. The first implementation in flutter#11143 created fresh page and navigator keys for every `ShellRouteMatch`. Review correctly pointed out that this made navigator identity unstable across route reparses and prevented the configured `ShellRoute.navigatorKey` from consistently identifying its navigator. `RoutingConfig` updates could also leave inactive loaded `StatefulShellRoute` branches holding matches and navigator widgets built from the old route objects. ## Fix This version addresses that feedback by: - preserving the configured navigator key during normal route matching and reparsing; - making shell page keys identity-aware, so distinct routes remain distinct even when their `hashCode` values collide; - keying the nested `_CustomNavigator` wrapper with a value-equal `ValueKey` of its navigator key; - assigning scoped page and navigator keys only when an imperative push would otherwise collide with another live regular `ShellRoute` match; - deriving that scope from the persistent `ImperativeRouteMatch.pageKey`; - carrying existing shell matches through recursive imperative push matching, so nested key collisions are detected; - reparsing loaded inactive `StatefulShellRoute` branches and rebuilding their cached navigator widgets when route objects change; - scoping saved matches to their shell and resetting branches whose base location was removed; - identifying reparsed branches by their navigator key, including after nested `pushReplacement()`; - preserving branch and root observers when rebuilding inactive or preloaded navigators, honoring `notifyRootObserver`; - leaving the root navigator wrapper and normal configured-key navigation unchanged. ## Tests The regression test `push to a sibling shell route under the same parent shell route` forces both navigator-key and route-hash collisions. It covers: - pushing to a sibling shell route; - re-entering the first shell route while its original instance is still in the stack; - preserving navigator and page state across match-list reconstruction and `refresh()`; - detecting and scoping collisions in nested `ShellRouteMatch` trees; - popping back through both shell routes; - navigating with `go()` after the imperative stack is removed. Additional regressions cover the nested push sequence in [the review comment](flutter/packages#12549 (comment)), inactive loaded branches after a `RoutingConfig` update ([review comment](flutter/packages#12549 (comment))), and the exact flows from flutter#148712 and flutter#140586. Eight additional regression cases cover the follow-up review findings: a removed base route with a surviving push (with and without preload), nested `pushReplacement()`, a removed pushed route, and branch/root observer behavior for both preload and `notifyRootObserver` settings. The observer regression uses pageless `Navigator.push()` so a GoRouter rebuild cannot mask detached observers; it also verifies navigator-state preservation and updated `clipBehavior`. No screenshots are included because this is a routing/runtime fix. - Fixes flutter#148712 - Fixes flutter#140586 ## Validation - `flutter test --no-pub`: 471 passed - `flutter analyze --no-pub`: no issues - `flutter_plugin_tools validate --check-for-missing-changes --packages go_router`: no issues - `flutter_plugin_tools publish-check --packages go_router`: no issues - License check: passed Release note: This package uses batch releases, so the fix is recorded in `pending_changelogs/shell_route_key_collisions.yaml`; `pubspec.yaml` and `CHANGELOG.md` remain unchanged. ## Pre-Review Checklist [^1]: Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling.
1 parent 975717a commit 17e14c2

9 files changed

Lines changed: 1315 additions & 68 deletions

File tree

‎packages/go_router/lib/src/builder.dart‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -344,7 +344,7 @@ class _CustomNavigatorState extends State<_CustomNavigator> {
344344
canPop: match.matches.length == 1,
345345
child: _CustomNavigator(
346346
// The state needs to persist across rebuild.
347-
key: GlobalObjectKey(navigatorKey.hashCode),
347+
key: ValueKey<GlobalKey<NavigatorState>>(navigatorKey),
348348
navigatorRestorationId: restorationScopeId,
349349
navigatorKey: navigatorKey,
350350
matches: match.matches,

‎packages/go_router/lib/src/match.dart‎

Lines changed: 97 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ abstract class RouteMatchBase with Diagnosticable {
174174
// have at least one match for this ShellRouteBase.
175175
matches: subRouteMatches!.remove(null)!,
176176
matchedLocation: remainingLocation,
177-
pageKey: ValueKey<String>(route.hashCode.toString()),
177+
pageKey: _ShellRoutePageKey(route),
178178
navigatorKey: navigatorKeyUsed,
179179
);
180180
subRouteMatches.putIfAbsent(parentKey, () => <RouteMatchBase>[]).insert(0, result);
@@ -336,6 +336,49 @@ class RouteMatch extends RouteMatchBase {
336336
}
337337
}
338338

339+
class _ShellRoutePageKey extends ValueKey<String> {
340+
_ShellRoutePageKey(ShellRouteBase route, [ValueKey<String>? imperativePageKey])
341+
: _routeIdentity = route.pageIdentity,
342+
_imperativePageKey = imperativePageKey,
343+
super(
344+
imperativePageKey == null
345+
? route.pageIdentity.hashCode.toString()
346+
: '${route.pageIdentity.hashCode}-${imperativePageKey.value}',
347+
);
348+
349+
final Object _routeIdentity;
350+
final ValueKey<String>? _imperativePageKey;
351+
352+
@override
353+
bool operator ==(Object other) {
354+
return other is _ShellRoutePageKey &&
355+
other._routeIdentity == _routeIdentity &&
356+
other._imperativePageKey == _imperativePageKey;
357+
}
358+
359+
@override
360+
int get hashCode => Object.hash(_routeIdentity.hashCode, _imperativePageKey);
361+
}
362+
363+
class _ShellRouteNavigatorKey extends GlobalKey<NavigatorState> {
364+
_ShellRouteNavigatorKey(ShellRouteBase route, this.imperativePageKey)
365+
: _routeIdentity = route.pageIdentity,
366+
super.constructor();
367+
368+
final Object _routeIdentity;
369+
final ValueKey<String> imperativePageKey;
370+
371+
@override
372+
bool operator ==(Object other) {
373+
return other is _ShellRouteNavigatorKey &&
374+
other._routeIdentity == _routeIdentity &&
375+
other.imperativePageKey == imperativePageKey;
376+
}
377+
378+
@override
379+
int get hashCode => Object.hash(_routeIdentity.hashCode, imperativePageKey);
380+
}
381+
339382
/// An matched result by matching a [ShellRoute] against a location.
340383
///
341384
/// This is typically created by calling [RouteMatchBase.match].
@@ -404,13 +447,17 @@ class ShellRouteMatch extends RouteMatchBase {
404447
// TODO(loic-sharma): Remove meta library prefix.
405448
// https://github.com/flutter/flutter/issues/171410
406449
@meta.internal
407-
ShellRouteMatch copyWith({required List<RouteMatchBase>? matches}) {
450+
ShellRouteMatch copyWith({
451+
required List<RouteMatchBase>? matches,
452+
ValueKey<String>? pageKey,
453+
GlobalKey<NavigatorState>? navigatorKey,
454+
}) {
408455
return ShellRouteMatch(
409456
matches: matches ?? this.matches,
410457
route: route,
411458
matchedLocation: matchedLocation,
412-
pageKey: pageKey,
413-
navigatorKey: navigatorKey,
459+
pageKey: pageKey ?? this.pageKey,
460+
navigatorKey: navigatorKey ?? this.navigatorKey,
414461
);
415462
}
416463

@@ -616,9 +663,18 @@ class RouteMatchList with Diagnosticable {
616663
static List<RouteMatchBase> _createNewMatchUntilIncompatible(
617664
List<RouteMatchBase> currentMatches,
618665
List<RouteMatchBase> otherMatches,
619-
ImperativeRouteMatch match,
620-
) {
621-
final List<RouteMatchBase> newMatches = currentMatches.toList();
666+
ImperativeRouteMatch match, {
667+
List<ShellRouteMatch> ancestorShellRouteMatches = const <ShellRouteMatch>[],
668+
}) {
669+
final newMatches = <RouteMatchBase>[...currentMatches];
670+
// Shell matches outside a recursive branch can still reserve its keys.
671+
final existingShellRouteMatches = <ShellRouteMatch>[...ancestorShellRouteMatches];
672+
_visitRouteMatches(newMatches, (RouteMatchBase match) {
673+
if (match is ShellRouteMatch) {
674+
existingShellRouteMatches.add(match);
675+
}
676+
return true;
677+
});
622678
if (otherMatches.last is ShellRouteMatch &&
623679
newMatches.isNotEmpty &&
624680
otherMatches.last.route == newMatches.last.route) {
@@ -631,22 +687,52 @@ class RouteMatchList with Diagnosticable {
631687
lastShellRouteMatch.matches,
632688
(otherMatches.last as ShellRouteMatch).matches,
633689
match,
690+
ancestorShellRouteMatches: existingShellRouteMatches,
634691
),
635692
),
636693
);
637694
return newMatches;
638695
}
639-
newMatches.add(_cloneBranchAndInsertImperativeMatch(otherMatches.last, match));
696+
final RouteMatchBase branch = otherMatches.last;
697+
newMatches.add(
698+
_cloneBranchAndInsertImperativeMatch(
699+
branch,
700+
match,
701+
existingShellRouteMatches: existingShellRouteMatches,
702+
),
703+
);
640704
return newMatches;
641705
}
642706

643707
static RouteMatchBase _cloneBranchAndInsertImperativeMatch(
644708
RouteMatchBase branch,
645-
ImperativeRouteMatch match,
646-
) {
709+
ImperativeRouteMatch match, {
710+
required List<ShellRouteMatch> existingShellRouteMatches,
711+
}) {
647712
if (branch is ShellRouteMatch) {
713+
final bool scopeKeys =
714+
branch.route is ShellRoute &&
715+
existingShellRouteMatches.any(
716+
(ShellRouteMatch existingMatch) =>
717+
existingMatch.pageKey == branch.pageKey ||
718+
existingMatch.navigatorKey == branch.navigatorKey,
719+
);
720+
final ValueKey<String> pageKey = scopeKeys
721+
? _ShellRoutePageKey(branch.route, match.pageKey)
722+
: branch.pageKey;
723+
final GlobalKey<NavigatorState> navigatorKey = scopeKeys
724+
? _ShellRouteNavigatorKey(branch.route, match.pageKey)
725+
: branch.navigatorKey;
648726
return branch.copyWith(
649-
matches: <RouteMatchBase>[_cloneBranchAndInsertImperativeMatch(branch.matches.last, match)],
727+
matches: <RouteMatchBase>[
728+
_cloneBranchAndInsertImperativeMatch(
729+
branch.matches.last,
730+
match,
731+
existingShellRouteMatches: existingShellRouteMatches,
732+
),
733+
],
734+
pageKey: pageKey,
735+
navigatorKey: navigatorKey,
650736
);
651737
}
652738
// Add the input `match` instead of the incompatibleMatch since it contains

0 commit comments

Comments
 (0)