Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
56 changes: 53 additions & 3 deletions lib/src/router/controller/routing_controller.dart
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,18 @@ abstract class RoutingController with ChangeNotifier {
}
}

// Removes the child router attached to exactly [routeData]. Pages from the
// same route share a key, so only fall back to the key when one is given.
void _removeChildRouterOf(RouteData routeData, {Key? fallbackKey}) {
final ctr = _childControllers
.lastWhereOrNull((c) => identical(c.routeData, routeData));
if (ctr != null) {
_childControllers.remove(ctr);
} else if (fallbackKey != null) {
_removeTopRouterOf(fallbackKey);
}
}

UrlState get urlState => navigationHistory.urlState;

String get currentPath => urlState.path;
Expand Down Expand Up @@ -680,8 +692,11 @@ abstract class StackRouter extends RoutingController {
}

void _removeRedirectGuard(RedirectGuardBase guard) {
guard.removeListener(_redirectGuardsListeners[guard]!);
_redirectGuardsListeners.remove(guard);
// Tolerates being called for a guard this router never attached (or
// already detached): removal cleanup must stay idempotent.
final listener = _redirectGuardsListeners.remove(guard);
if (listener == null) return;
guard.removeListener(listener);
}

@override
Expand Down Expand Up @@ -868,21 +883,56 @@ abstract class StackRouter extends RoutingController {

void _removeRoute(RouteMatch route, {bool notify = true}) {
var pageIndex = _pages.lastIndexWhere((p) => p.routeKey == route.key);
RouteData? routeData;
if (pageIndex != -1) {
routeData = _pages[pageIndex].routeData;
_pages.removeAt(pageIndex);
}
_detachRedirectGuards(route);
_updateSharedPathData(includeAncestors: true);
if (routeData != null) {
_removeChildRouterOf(routeData, fallbackKey: route.key);
} else {
_removeTopRouterOf(route.key);
}
if (notify) {
notifyAll(forceUrlRebuild: true);
}
}

void _detachRedirectGuards(RouteMatch route) {
final stack = _pages.map((e) => e.routeData._match);
for (final guard in route.guards.whereType<RedirectGuard>()) {
if (!stack.any((r) => r.guards.contains(guard))) {
_removeRedirectGuard(guard);
}
}
}

// Removes [page] by identity rather than by (possibly shared) routeKey.
// Does nothing and returns false if it is not currently in the stack.
@internal
bool removePageInstance(StackedPage page, {bool notify = true}) {
final pageIndex = _pages.indexWhere((p) => identical(p, page));
if (pageIndex == -1) return false;
_pages.removeAt(pageIndex);
final route = page.routeData._match;
_detachRedirectGuards(route);
_updateSharedPathData(includeAncestors: true);
_removeTopRouterOf(route.key);
_removeChildRouterOf(page.routeData, fallbackKey: route.key);
if (notify) {
notifyAll(forceUrlRebuild: true);
}
return true;
}

// Cleanup for a page that already left the stack. Only detaches what is
// still attached to that exact page, so running it after
// [removePageInstance] is a no-op and never touches a sibling page.
@internal
void finishRemovedRouteCleanup(RouteData routeData) {
_detachRedirectGuards(routeData._match);
_removeChildRouterOf(routeData);
}

@override
Expand Down
29 changes: 25 additions & 4 deletions lib/src/router/stacked_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) {

Copy link
Copy Markdown
Contributor

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 createRoute makes 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:

  • _popCompleter never completes, so await router.push<T>(...) / page.popped hangs forever (a silent deadlock, which is arguably worse than the Bad state it replaces).
  • the eager removePageInstance(this) below never runs, so the page stays in router.stack while its route is gone; currentUrl and canPop() are then wrong.
  • B is a phantom route nobody will ever pop, so nothing recovers.

_popCompleter.isCompleted alone 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 the isCompleted guard, and making the eager removal run on whichever route completes first.

Copy link
Copy Markdown
Contributor

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 identical check trades it for a worse failure.

_popCompleter.isCompleted alone is order-independent, agreed — but it also lets a stale route win. If createRoute ran twice and the discarded route completes while the page is still live, we would complete popped with that route's result and eagerly removePageInstance a page that is still on screen. That is exactly what the guard was added for in 9c7d631, and the regression test in stacked_page_test.dart asserts it: routeA.didPop('stale-result') then routeB.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 _TestRoute is installed in a Navigator.

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.

Copy link
Copy Markdown
Collaborator Author

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.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Eager removal of the last page empties _pages mid-animation, which swaps the whole Navigator out for the placeholder.

RouteNavigator.build is:

final navigator = widget.router.hasEntries ? Navigator(...) : widget.placeholder?.call(context) ?? Container(color: ...);

and hasEntries => _pages.isNotEmpty. Removing the page at pop start (rather than after the route is disposed) plus notifyAll(forceUrlRebuild: true) means that when the popped page is the only one left, the next rebuild replaces the Navigator with the placeholder Container while the exit animation is still running.

Scenario: a nested router whose stack is [Details] inside a tab, and something calls router.pop() (or the nested PopScope path in this same file forwards a back gesture). Instead of the route animating out, the whole nested navigator vanishes in one frame — and because the Navigator is disposed rather than told the page went away, onDidRemovePage never fires, so widget.didPop?.call(routeData.route, null) is never invoked and any pageless routes (dialogs/bottom sheets) on that navigator are torn down without their observers running.

Worth deferring the eager removal to after the route's exit animation when it would empty the stack, or keeping the Navigator mounted while a pop is in flight.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 popForced(), sampling immediately after the pop.

  • PR head 1e71dc1: stack=0 hasEntries=false navigators=0
  • Pre-PR base b0bc379: stack=0 hasEntries=false navigators=0

Identical. The old handler already called widget.router.removeRoute(routeData) from onDidRemovePage, which Flutter invokes synchronously inside handlePop at pop start (Route.didComplete is documented to resolve popped "before the pop animation, if any, takes place"). So _pages was already emptied at the same moment before this change.

The eager removePageInstance cannot cause it, because it runs on a later microtask, by which point onDidRemovePage has already removed the page and it returns false.

Worth fixing on its own, but it is out of scope for this PR.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The 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, popForced(), sampled one frame in:

  • master: stack=1 hasEntries=true navigators=1, the page animates out.
  • PR head: stack=0 hasEntries=false navigators=0, the Navigator is gone immediately.

In b06f841 the eager removal is skipped when the page is the last one on the stack, so onDidRemovePage handles that case as before. Covered by a unit test in stacked_page_test.dart.

}
});
return route;
}
}

Expand Down
6 changes: 5 additions & 1 deletion lib/src/router/widgets/route_navigator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Crash: _finishRouteRemoval now runs twice per animated pop, and the redirect-guard cleanup is not idempotent.

On a normal animated pop the eager path in StackedPage.createRoute already ran removePageInstance -> _finishRouteRemoval. When the exit animation ends, onDidRemovePage fires, removePageInstance returns false, and this line runs _finishRouteRemoval a second time for the same RouteMatch.

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 RedirectGuard (e.g. AuthGuard extends RedirectGuard) is the only page carrying that guard, and the user pops it. First pass: the guard is absent from the remaining stack, so _removeRedirectGuard removes it from _redirectGuardsListeners. Second pass (this line, ~300ms later when the route is disposed): the guard is still absent from the stack, so _removeRedirectGuard is called again and _redirectGuardsListeners[guard]! throws Null check operator used on a null value.

Before this PR _removeRoute ran once per removal, so this path was not reachable on an ordinary pop. Suggest guarding removal (_redirectGuardsListeners.remove(guard)?.let(guard.removeListener)-style) and/or making finishRemovedRouteCleanup skip work it already did.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 packages/flutter/lib/src/widgets/navigator.dart, _RouteEntry.handlePop:

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
}

Route.popped.then(...) callbacks only run on a later microtask, so onDidRemovePage always runs first. That means this handler is the one that removes the page and runs the cleanup, and the eager removePageInstance in StackedPage.createRoute is the call that returns false.

Verified empirically: I added a print at the top of _finishRouteRemoval and ran the full suite — exactly one call per removal, never two, and finishRemovedRouteCleanup never fired at all across 101 tests.

That said, relying on Flutter's internal ordering for idempotency is fragile, so I made _removeRedirectGuard tolerate a missing listener instead of using _redirectGuardsListeners[guard]! — pushed as f1c31b5.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The 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 navigator.dart per tag:

Flutter onDidRemovePage is called from
3.35 handlePop, at pop start
3.38, 3.41 _flushHistoryUpdates, at the dispose stage, after the exit animation
3.44, 3.47 handlePop, at pop start

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 finishRemovedRouteCleanup fired once. The pubspec only requires Dart 3.5, so those Flutter versions are in range.

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);
}
},
Expand Down
77 changes: 77 additions & 0 deletions test/router/nested_sibling_router_test.dart
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);
},
);
}
Loading
Loading