Repository navigation
fix(router): guard StackedPage pop completer and remove popped page by identity #1197
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
base: master
Are you sure you want to change the base?
Changes from all commits
9c7d631
ba03fc6
829fb23
1e71dc1
f1c31b5
b06f841
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -19,6 +19,9 @@ abstract class StackedPage<T> extends Page<T> { | |
|
|
||
| final _popCompleter = Completer<T?>(); | ||
|
|
||
| // Latest route created for this page. Boxed because [Page] is immutable. | ||
| final _latestRouteBox = List<Route<T>?>.filled(1, null); | ||
|
|
||
| Future<T?> get popped => _popCompleter.future; | ||
|
|
||
| Widget get child => _child; | ||
|
|
@@ -60,10 +63,28 @@ abstract class StackedPage<T> extends Page<T> { | |
|
|
||
| @override | ||
| Route<T> createRoute(BuildContext context) { | ||
| return onCreateRoute(context) | ||
| ..popped.then( | ||
| _popCompleter.complete, | ||
| ); | ||
| final route = onCreateRoute(context); | ||
| _latestRouteBox[0] = route; | ||
| route.popped.then((result) { | ||
| // createRoute can run more than once per page; only the latest route | ||
| // may complete the completer, and only once. | ||
| if (!identical(route, _latestRouteBox[0]) || _popCompleter.isCompleted) { | ||
| return; | ||
| } | ||
| _popCompleter.complete(result); | ||
|
|
||
| // Remove this exact page now rather than waiting for onDidRemovePage, | ||
| // so the Navigator cannot rebuild with a stale page and recreate its | ||
| // route. Identity-based: a shared routeKey must not remove a sibling. | ||
| // Skipped for the last page: emptying the stack now would swap the | ||
| // Navigator for the placeholder mid-animation. onDidRemovePage | ||
| // handles that case. | ||
| final router = routeData.router; | ||
| if (router is StackRouter && router.stack.length > 1) { | ||
| router.removePageInstance(this); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Eager removal of the last page empties
final navigator = widget.router.hasEntries ? Navigator(...) : widget.placeholder?.call(context) ?? Container(color: ...);and Scenario: a nested router whose stack is Worth deferring the eager removal to after the route's exit animation when it would empty the stack, or keeping the
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This behaviour is real, but it predates the PR — the eager removal is not the actor. Same test on both revisions: root router with a single page, then
Identical. The old handler already called The eager Worth fixing on its own, but it is out of scope for this PR.
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Pre-existing on 3.47 and 3.35, agreed, but on 3.38 and 3.41 it is new behaviour from this PR. Same probe on 3.41.7, single-page root,
In b06f841 the eager removal is skipped when the page is the last one on the stack, so |
||
| } | ||
| }); | ||
| return route; | ||
| } | ||
| } | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -74,7 +74,11 @@ class RouteNavigatorState extends State<RouteNavigator> { | |||||||||
| onDidRemovePage: (page) { | ||||||||||
| if (page is StackedPage) { | ||||||||||
| var routeData = page.routeData; | ||||||||||
| widget.router.removeRoute(routeData); | ||||||||||
| // By identity: a shared routeKey must not remove a sibling | ||||||||||
| // page pushed from the same route. | ||||||||||
| if (!widget.router.removePageInstance(page)) { | ||||||||||
| widget.router.finishRemovedRouteCleanup(routeData); | ||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Crash: On a normal animated pop the eager path in The guard loop inside it is not idempotent: void _removeRedirectGuard(RedirectGuardBase guard) {
guard.removeListener(_redirectGuardsListeners[guard]!); // <-- null check
_redirectGuardsListeners.remove(guard);
}Scenario: a route protected by a Before this PR
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Checked this against Flutter 3.47.2 and it does not reproduce — the ordering is the other way around. In route.didPop(pendingResult); // completes Route.popped
route.onPopInvokedWithResult(true, pendingResult);
if (pageBased && imperativeRemoval) {
final page = route.settings as Page<Object?>;
navigator.widget.onDidRemovePage?.call(page); // synchronous, same call
}
Verified empirically: I added a That said, relying on Flutter's internal ordering for idempotency is fragile, so I made
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Your ordering holds on Flutter 3.44 and later (and on 3.35), but not on every supported version. I checked
On 3.38 and 3.41 the order flips: the eager path does the real removal and this fallback runs the cleanup a second time. I replayed your print experiment on 3.41.7 against the same suite: the eager path removed the page 3 times and Thanks for the idempotent guard change, kept as is. In b06f841 the fallback now only detaches what is still attached to that exact page (guards and its own child router), so a second pass is a no-op. CI only runs on the latest stable, so it cannot see this; a second job on an older Flutter would catch this class of issue. |
||||||||||
| } | ||||||||||
| widget.didPop?.call(routeData.route, null); | ||||||||||
| } | ||||||||||
| }, | ||||||||||
|
|
||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| import 'dart:async'; | ||
|
|
||
| import 'package:flutter/material.dart'; | ||
| import 'package:flutter_test/flutter_test.dart'; | ||
| import 'package:stacked/stacked.dart'; | ||
|
|
||
| class _Text extends StatelessWidget { | ||
| const _Text(this.text); | ||
| final String text; | ||
| @override | ||
| Widget build(BuildContext context) => Scaffold(body: Text(text)); | ||
| } | ||
|
|
||
| class _DetailScreen extends StatelessWidget { | ||
| const _DetailScreen(); | ||
| @override | ||
| Widget build(BuildContext context) => const Scaffold(body: NestedRouter()); | ||
| } | ||
|
|
||
| class _TestRouter extends RootStackRouter { | ||
| @override | ||
| late final Map<String, PageFactory> pagesMap = { | ||
| 'HomeRoute': (d) => MaterialPageX(routeData: d, child: const _Text('Home')), | ||
| 'DetailRoute': (d) => | ||
| MaterialPageX(routeData: d, child: const _DetailScreen()), | ||
| 'InnerRoute': (d) => | ||
| MaterialPageX(routeData: d, child: const _Text('Inner')), | ||
| }; | ||
|
|
||
| @override | ||
| List<RouteConfig> get routes => [ | ||
| RouteConfig('HomeRoute', path: '/', fullMatch: true), | ||
| RouteConfig('DetailRoute', path: '/detail/:id', children: [ | ||
| RouteConfig('InnerRoute', path: '', fullMatch: true), | ||
| ]), | ||
| ]; | ||
| } | ||
|
|
||
| PageRouteInfo _detail(int id) => PageRouteInfo<int>( | ||
| 'DetailRoute', | ||
| path: '/detail/$id', | ||
| args: id, | ||
| rawPathParams: {'id': id}, | ||
| initialChildren: const [PageRouteInfo('InnerRoute', path: '')], | ||
| ); | ||
|
|
||
| void main() { | ||
| testWidgets( | ||
| 'popping a page keeps the nested router of a sibling page from the same route', | ||
| (tester) async { | ||
| final router = _TestRouter(); | ||
| await tester.pumpWidget(MaterialApp.router( | ||
| routerDelegate: router.delegate( | ||
| initialRoutes: [const PageRouteInfo('HomeRoute', path: '/')], | ||
| ), | ||
| routeInformationParser: router.defaultRouteParser(), | ||
| routeInformationProvider: router.routeInfoProvider(), | ||
| )); | ||
| await tester.pumpAndSettle(); | ||
|
|
||
| unawaited(router.push(_detail(1))); | ||
| await tester.pumpAndSettle(); | ||
| unawaited(router.push(_detail(2))); | ||
| await tester.pumpAndSettle(); | ||
| expect(router.stack, hasLength(3)); | ||
| expect(router.childControllers, hasLength(2)); | ||
|
|
||
| unawaited(router.pop()); | ||
| await tester.pumpAndSettle(); | ||
|
|
||
| expect(router.stack, hasLength(2)); | ||
| expect(router.childControllers, hasLength(1)); | ||
| expect(router.childControllers.single.routeData.args, 1); | ||
| expect(router.innerRouterOf('DetailRoute'), isNotNull); | ||
| }, | ||
| ); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
identical(route, _latestRouteBox[0])guard is the wrong way round for the very race it is meant to cover: if the phantom route is created before the real route pops, the pop is dropped forever.The PR description's own root cause is that the Navigator can rebuild with the stale page and create a second route for it. The guard assumes the live route is always the latest one created. If the order is reversed — route A is on screen and mid-gesture, the Navigator rebuilds and
createRoutemakes route B (so_latestRouteBox[0] == B), and only then does A's predictive-back gesture commit — A's callback hits!identical(route, _latestRouteBox[0])and returns early.Consequences in that ordering:
_popCompleternever completes, soawait router.push<T>(...)/page.poppedhangs forever (a silent deadlock, which is arguably worse than theBad stateit replaces).removePageInstance(this)below never runs, so the page stays inrouter.stackwhile its route is gone;currentUrlandcanPop()are then wrong._popCompleter.isCompletedalone is sufficient to stop the double-complete and is order-independent — first pop wins, later ones are ignored. Recommend dropping the identity check and keeping only theisCompletedguard, and making the eager removal run on whichever route completes first.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This one is a fair concern, but dropping the
identicalcheck trades it for a worse failure._popCompleter.isCompletedalone is order-independent, agreed — but it also lets a stale route win. IfcreateRouteran twice and the discarded route completes while the page is still live, we would completepoppedwith that route's result and eagerlyremovePageInstancea page that is still on screen. That is exactly what the guard was added for in 9c7d631, and the regression test instacked_page_test.dartasserts it:routeA.didPop('stale-result')thenrouteB.didPop('latest-result')must resolve to'latest-result'.I also tried a middle ground — ignore the superseded route only when the newer one is actually installed (
_latestRouteBox[0]?.navigator != null) — which would fix the phantom case while keeping stale-route protection. It fails that same test, because in the test harness neither_TestRouteis installed in aNavigator.The hang needs a route that is created, never installed, and never popped. I could not construct it. Leaving the guard as-is unless someone has a reproduction.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Agree, keeping the identity check. The phantom route can only be created once the real route's history entry has been disposed, which happens in a later frame, while this callback runs as a microtask right after
didPop. So the real route always sees itself as the latest one. The stale-route protection is worth more than a case I could not construct either.