From 9c7d631e65aa06b8a6bc0f0f7c268958dae8f5f2 Mon Sep 17 00:00:00 2001 From: Eimen2018 Date: Fri, 18 Sep 2026 01:12:20 +0400 Subject: [PATCH 1/6] fix(router): guard StackedPage pop completer against double completion Flutter can call createRoute more than once for the same Page instance (page reuse / predictive back). The single _popCompleter was then completed twice, throwing 'Bad state: Future already completed' on Android back gestures. Fixes #1181 Co-Authored-By: Claude Fable 5.1 --- lib/src/router/stacked_page.dart | 32 +++++++- test/router/stacked_page_test.dart | 124 +++++++++++++++++++++++++++++ 2 files changed, 152 insertions(+), 4 deletions(-) create mode 100644 test/router/stacked_page_test.dart diff --git a/lib/src/router/stacked_page.dart b/lib/src/router/stacked_page.dart index a4b97652..0e7888db 100644 --- a/lib/src/router/stacked_page.dart +++ b/lib/src/router/stacked_page.dart @@ -19,6 +19,20 @@ abstract class StackedPage extends Page { final _popCompleter = Completer(); + /// Boxed reference to the most recently created [Route] for this page. + /// + /// Flutter's Navigator can call [createRoute] more than once for the same + /// [StackedPage] instance (e.g. when a page is briefly recreated during a + /// predictive back gesture that gets cancelled, or through other page + /// reuse scenarios). We keep track of the latest route here so that only + /// its pop result is ever forwarded through [popped], and so a stale route + /// created by an earlier call can't complete [_popCompleter] a second time. + /// + /// This is boxed in a single-element, `final` list (instead of a plain + /// mutable field) because [StackedPage] extends the `@immutable`-annotated + /// [Page], which requires every instance field to be `final`. + final _latestRouteBox = List?>.filled(1, null); + Future get popped => _popCompleter.future; Widget get child => _child; @@ -60,10 +74,20 @@ abstract class StackedPage extends Page { @override Route createRoute(BuildContext context) { - return onCreateRoute(context) - ..popped.then( - _popCompleter.complete, - ); + final route = onCreateRoute(context); + _latestRouteBox[0] = route; + route.popped.then((result) { + // Guard against this being a stale route from an earlier call to + // createRoute (only the latest route's result should ever be + // forwarded) and against _popCompleter already being completed by a + // previous call. Without these checks, Flutter calling createRoute + // more than once for the same page instance can complete the same + // completer twice, throwing "Bad state: Future already completed". + if (identical(route, _latestRouteBox[0]) && !_popCompleter.isCompleted) { + _popCompleter.complete(result); + } + }); + return route; } } diff --git a/test/router/stacked_page_test.dart b/test/router/stacked_page_test.dart new file mode 100644 index 00000000..92c53e7e --- /dev/null +++ b/test/router/stacked_page_test.dart @@ -0,0 +1,124 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:stacked/src/router/controller/routing_controller.dart'; +import 'package:stacked/src/router/matcher/route_match.dart'; +import 'package:stacked/src/router/stacked_page.dart'; + +/// Minimal stand-in for [RoutingController]. +/// +/// [RoutingController] is abstract and pulls in the whole routing stack, but +/// [RouteData] only stores the reference without calling anything on it +/// during the scenario under test, so a `noSuchMethod`-backed fake is enough. +class _FakeRoutingController implements RoutingController { + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +/// A bare-bones [Route] with none of [PageRoute]'s animation-controller +/// machinery, so tests can drive [didPop]/[didComplete] directly without +/// installing the route into a real [Navigator]. +class _TestRoute extends Route { + _TestRoute({required RouteSettings settings}) : super(settings: settings); +} + +/// A minimal concrete [StackedPage] used purely to exercise `createRoute`. +class _TestPage extends StackedPage { + _TestPage({required super.routeData, required super.child}); + + @override + Route onCreateRoute(BuildContext context) => _TestRoute(settings: this); +} + +RouteData _buildRouteData(String name) { + final match = RouteMatch( + name: name, + segments: [name], + path: '/$name', + stringMatch: '/$name', + key: ValueKey(name), + ); + return RouteData( + route: match, + router: _FakeRoutingController(), + pendingChildren: const [], + ); +} + +void main() { + group('StackedPage', () { + testWidgets( + 'createRoute called twice on the same page instance does not complete ' + 'popped twice (regression test for #1181)', + (WidgetTester tester) async { + await tester.pumpWidget(const MaterialApp(home: SizedBox())); + final context = tester.element(find.byType(SizedBox)); + + final page = _TestPage( + routeData: _buildRouteData('test'), + child: const SizedBox(), + ); + + // Flutter's Navigator can call createRoute more than once for the + // same Page instance (e.g. page reuse during a predictive back + // gesture that gets recreated/cancelled). Simulate that here. + final routeA = page.createRoute(context); + final routeB = page.createRoute(context); + + expect(routeA, isNot(same(routeB))); + + // Completing the stale (first) route must not throw, and must not + // be the value that resolves `popped`. + expect(() => routeA.didPop('stale-result'), returnsNormally); + + // Completing the real (latest) route must also not throw, even + // though the stale route already completed above. Before the fix, + // this would throw "Bad state: Future already completed". + expect(() => routeB.didPop('latest-result'), returnsNormally); + + // Only the latest route's result should ever be forwarded. + await expectLater(page.popped, completion('latest-result')); + }, + ); + + testWidgets( + 'createRoute called once still forwards the pop result as before', + (WidgetTester tester) async { + await tester.pumpWidget(const MaterialApp(home: SizedBox())); + final context = tester.element(find.byType(SizedBox)); + + final page = _TestPage( + routeData: _buildRouteData('single'), + child: const SizedBox(), + ); + + final route = page.createRoute(context); + route.didPop('the-result'); + + await expectLater(page.popped, completion('the-result')); + }, + ); + + testWidgets( + 'completing the stale route after the latest route already completed ' + 'does not throw', + (WidgetTester tester) async { + await tester.pumpWidget(const MaterialApp(home: SizedBox())); + final context = tester.element(find.byType(SizedBox)); + + final page = _TestPage( + routeData: _buildRouteData('reverse-order'), + child: const SizedBox(), + ); + + final routeA = page.createRoute(context); + final routeB = page.createRoute(context); + + // Complete the latest route first this time. + routeB.didPop('latest-result'); + expect(() => routeA.didPop('stale-result'), returnsNormally); + + await expectLater(page.popped, completion('latest-result')); + }, + ); + }); +} From ba03fc6cb199a44b03bbccc89a37329868cdbf14 Mon Sep 17 00:00:00 2001 From: Eimen2018 Date: Fri, 18 Sep 2026 01:20:50 +0400 Subject: [PATCH 2/6] fix(router): eagerly remove popped page from router stack Building on the earlier latest-route + isCompleted guard, also remove the popped page from the router's stack as soon as its route resolves, instead of only relying on the async onDidRemovePage callback in RouteNavigator. Flutter's Navigator can rebuild in the window between a pop and that callback (routinely during an Android predictive-back gesture); if `_pages` still contains the page with no live Route behind it, the Navigator calls createRoute again for the same Page, creating a second, phantom Route. That phantom route is what also produced the forward-transition flash on cancelled/predictive back gestures. The removal happens inside a Future.then callback (a microtask that only runs after the current synchronous call stack, including any in-progress frame's build/layout/paint, has unwound), so calling removeRoute with notify: true here does not run during a build phase. This is unlike the pre-existing, unrelated onDidRemovePage callback, which Flutter can invoke synchronously mid-build (see issue #1184, a separate, already-tracked bug); that hazard is untouched by this change. removeRoute's internal _removeRoute is also idempotent (a no-op when the page was already removed), so the later onDidRemovePage call for the same page remains safe. Only the latest route (per the existing guard) triggers the removal, so a stale route from an earlier createRoute call can neither forward a stale pop result nor prematurely remove the page. Approach based on #1188 by @Vinsho. Co-Authored-By: Claude Fable 5.1 --- lib/src/router/stacked_page.dart | 24 +++++++- test/router/stacked_page_test.dart | 93 +++++++++++++++++++++++++++++- 2 files changed, 113 insertions(+), 4 deletions(-) diff --git a/lib/src/router/stacked_page.dart b/lib/src/router/stacked_page.dart index 0e7888db..373323e8 100644 --- a/lib/src/router/stacked_page.dart +++ b/lib/src/router/stacked_page.dart @@ -83,8 +83,28 @@ abstract class StackedPage extends Page { // previous call. Without these checks, Flutter calling createRoute // more than once for the same page instance can complete the same // completer twice, throwing "Bad state: Future already completed". - if (identical(route, _latestRouteBox[0]) && !_popCompleter.isCompleted) { - _popCompleter.complete(result); + if (!identical(route, _latestRouteBox[0]) || _popCompleter.isCompleted) { + return; + } + _popCompleter.complete(result); + + // Eagerly remove this page from the router's stack instead of relying + // only on the async `onDidRemovePage` callback in RouteNavigator. The + // Navigator can rebuild between this pop and that callback (routinely + // during an Android predictive-back gesture). If `_pages` still holds + // this page with no live Route behind it, the Navigator calls + // createRoute again and produces a phantom second Route, which caused + // the forward-transition flash on back gestures. `removeRoute` is + // idempotent, so the later onDidRemovePage call is a harmless no-op. + // + // This runs in a `Future.then` microtask, after the synchronous call + // stack (including any in-progress frame) has unwound, so notifying + // listeners here does not happen during a build. + // + // Approach based on #1188 by @Vinsho. + final router = routeData.router; + if (router is StackRouter) { + router.removeRoute(routeData, notify: true); } }); return route; diff --git a/test/router/stacked_page_test.dart b/test/router/stacked_page_test.dart index 92c53e7e..3a68e082 100644 --- a/test/router/stacked_page_test.dart +++ b/test/router/stacked_page_test.dart @@ -14,6 +14,33 @@ class _FakeRoutingController implements RoutingController { dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } +/// Records a single call made to [_FakeStackRouter.removeRoute]. +class _RemoveRouteCall { + const _RemoveRouteCall(this.route, {required this.notify}); + final RouteData route; + final bool notify; +} + +/// A [StackRouter] test double that records calls to [removeRoute] instead +/// of actually maintaining a page stack. +/// +/// Standing up a real [StackRouter] would require a full route +/// collection/matcher/page-builder setup unrelated to what's under test +/// here: whether [StackedPage.createRoute] asks the router to remove the +/// page eagerly, with the right arguments, only for the route that actually +/// popped. +class _FakeStackRouter implements StackRouter { + final List<_RemoveRouteCall> removeRouteCalls = []; + + @override + void removeRoute(RouteData route, {bool notify = true}) { + removeRouteCalls.add(_RemoveRouteCall(route, notify: notify)); + } + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + /// A bare-bones [Route] with none of [PageRoute]'s animation-controller /// machinery, so tests can drive [didPop]/[didComplete] directly without /// installing the route into a real [Navigator]. @@ -29,7 +56,7 @@ class _TestPage extends StackedPage { Route onCreateRoute(BuildContext context) => _TestRoute(settings: this); } -RouteData _buildRouteData(String name) { +RouteData _buildRouteData(String name, {RoutingController? router}) { final match = RouteMatch( name: name, segments: [name], @@ -39,7 +66,7 @@ RouteData _buildRouteData(String name) { ); return RouteData( route: match, - router: _FakeRoutingController(), + router: router ?? _FakeRoutingController(), pendingChildren: const [], ); } @@ -120,5 +147,67 @@ void main() { await expectLater(page.popped, completion('latest-result')); }, ); + + testWidgets( + 'popping the route eagerly removes the page from the router stack, ' + 'without waiting for onDidRemovePage (regression test for the ' + 'phantom-Route/forward-flash glitch; approach based on #1188 by ' + '@Vinsho)', + (WidgetTester tester) async { + await tester.pumpWidget(const MaterialApp(home: SizedBox())); + final context = tester.element(find.byType(SizedBox)); + + final router = _FakeStackRouter(); + final routeData = _buildRouteData('predictive-back', router: router); + final page = _TestPage( + routeData: routeData, + child: const SizedBox(), + ); + + final route = page.createRoute(context); + route.didPop('the-result'); + + // Nothing resembling RouteNavigator's `onDidRemovePage` callback is + // ever invoked in this test, yet the router must already have been + // asked to remove the page by the time `popped` resolves. + await expectLater(page.popped, completion('the-result')); + + expect(router.removeRouteCalls, hasLength(1)); + expect(router.removeRouteCalls.single.route, same(routeData)); + expect(router.removeRouteCalls.single.notify, isTrue); + }, + ); + + testWidgets( + 'createRoute called twice only removes the page from the router once, ' + 'for the latest route, and not for the stale one', + (WidgetTester tester) async { + await tester.pumpWidget(const MaterialApp(home: SizedBox())); + final context = tester.element(find.byType(SizedBox)); + + final router = _FakeStackRouter(); + final routeData = _buildRouteData('predictive-back-2', router: router); + final page = _TestPage( + routeData: routeData, + child: const SizedBox(), + ); + + final routeA = page.createRoute(context); + final routeB = page.createRoute(context); + + // The stale route popping first must not touch the router at all. + routeA.didPop('stale-result'); + await Future.value(); + expect(router.removeRouteCalls, isEmpty); + + // The latest (real) route popping removes the page exactly once. + routeB.didPop('latest-result'); + await expectLater(page.popped, completion('latest-result')); + + expect(router.removeRouteCalls, hasLength(1)); + expect(router.removeRouteCalls.single.route, same(routeData)); + expect(router.removeRouteCalls.single.notify, isTrue); + }, + ); }); } From 829fb234ea10994f46c80222f6e8120aff5b338f Mon Sep 17 00:00:00 2001 From: Eimen2018 Date: Sat, 19 Sep 2026 01:23:54 +0400 Subject: [PATCH 3/6] chore: trim comments Co-Authored-By: Claude Fable 5.1 --- lib/src/router/stacked_page.dart | 37 ++++-------------------------- test/router/stacked_page_test.dart | 33 -------------------------- 2 files changed, 5 insertions(+), 65 deletions(-) diff --git a/lib/src/router/stacked_page.dart b/lib/src/router/stacked_page.dart index 373323e8..d04c990b 100644 --- a/lib/src/router/stacked_page.dart +++ b/lib/src/router/stacked_page.dart @@ -19,18 +19,7 @@ abstract class StackedPage extends Page { final _popCompleter = Completer(); - /// Boxed reference to the most recently created [Route] for this page. - /// - /// Flutter's Navigator can call [createRoute] more than once for the same - /// [StackedPage] instance (e.g. when a page is briefly recreated during a - /// predictive back gesture that gets cancelled, or through other page - /// reuse scenarios). We keep track of the latest route here so that only - /// its pop result is ever forwarded through [popped], and so a stale route - /// created by an earlier call can't complete [_popCompleter] a second time. - /// - /// This is boxed in a single-element, `final` list (instead of a plain - /// mutable field) because [StackedPage] extends the `@immutable`-annotated - /// [Page], which requires every instance field to be `final`. + // Latest route created for this page. Boxed because [Page] is immutable. final _latestRouteBox = List?>.filled(1, null); Future get popped => _popCompleter.future; @@ -77,31 +66,15 @@ abstract class StackedPage extends Page { final route = onCreateRoute(context); _latestRouteBox[0] = route; route.popped.then((result) { - // Guard against this being a stale route from an earlier call to - // createRoute (only the latest route's result should ever be - // forwarded) and against _popCompleter already being completed by a - // previous call. Without these checks, Flutter calling createRoute - // more than once for the same page instance can complete the same - // completer twice, throwing "Bad state: Future already completed". + // 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); - // Eagerly remove this page from the router's stack instead of relying - // only on the async `onDidRemovePage` callback in RouteNavigator. The - // Navigator can rebuild between this pop and that callback (routinely - // during an Android predictive-back gesture). If `_pages` still holds - // this page with no live Route behind it, the Navigator calls - // createRoute again and produces a phantom second Route, which caused - // the forward-transition flash on back gestures. `removeRoute` is - // idempotent, so the later onDidRemovePage call is a harmless no-op. - // - // This runs in a `Future.then` microtask, after the synchronous call - // stack (including any in-progress frame) has unwound, so notifying - // listeners here does not happen during a build. - // - // Approach based on #1188 by @Vinsho. + // Remove the page now rather than waiting for onDidRemovePage, so the + // Navigator cannot rebuild with a stale page and recreate its route. final router = routeData.router; if (router is StackRouter) { router.removeRoute(routeData, notify: true); diff --git a/test/router/stacked_page_test.dart b/test/router/stacked_page_test.dart index 3a68e082..ee714760 100644 --- a/test/router/stacked_page_test.dart +++ b/test/router/stacked_page_test.dart @@ -4,31 +4,17 @@ import 'package:stacked/src/router/controller/routing_controller.dart'; import 'package:stacked/src/router/matcher/route_match.dart'; import 'package:stacked/src/router/stacked_page.dart'; -/// Minimal stand-in for [RoutingController]. -/// -/// [RoutingController] is abstract and pulls in the whole routing stack, but -/// [RouteData] only stores the reference without calling anything on it -/// during the scenario under test, so a `noSuchMethod`-backed fake is enough. class _FakeRoutingController implements RoutingController { @override dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } -/// Records a single call made to [_FakeStackRouter.removeRoute]. class _RemoveRouteCall { const _RemoveRouteCall(this.route, {required this.notify}); final RouteData route; final bool notify; } -/// A [StackRouter] test double that records calls to [removeRoute] instead -/// of actually maintaining a page stack. -/// -/// Standing up a real [StackRouter] would require a full route -/// collection/matcher/page-builder setup unrelated to what's under test -/// here: whether [StackedPage.createRoute] asks the router to remove the -/// page eagerly, with the right arguments, only for the route that actually -/// popped. class _FakeStackRouter implements StackRouter { final List<_RemoveRouteCall> removeRouteCalls = []; @@ -41,14 +27,10 @@ class _FakeStackRouter implements StackRouter { dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } -/// A bare-bones [Route] with none of [PageRoute]'s animation-controller -/// machinery, so tests can drive [didPop]/[didComplete] directly without -/// installing the route into a real [Navigator]. class _TestRoute extends Route { _TestRoute({required RouteSettings settings}) : super(settings: settings); } -/// A minimal concrete [StackedPage] used purely to exercise `createRoute`. class _TestPage extends StackedPage { _TestPage({required super.routeData, required super.child}); @@ -85,24 +67,15 @@ void main() { child: const SizedBox(), ); - // Flutter's Navigator can call createRoute more than once for the - // same Page instance (e.g. page reuse during a predictive back - // gesture that gets recreated/cancelled). Simulate that here. final routeA = page.createRoute(context); final routeB = page.createRoute(context); expect(routeA, isNot(same(routeB))); - // Completing the stale (first) route must not throw, and must not - // be the value that resolves `popped`. expect(() => routeA.didPop('stale-result'), returnsNormally); - // Completing the real (latest) route must also not throw, even - // though the stale route already completed above. Before the fix, - // this would throw "Bad state: Future already completed". expect(() => routeB.didPop('latest-result'), returnsNormally); - // Only the latest route's result should ever be forwarded. await expectLater(page.popped, completion('latest-result')); }, ); @@ -140,7 +113,6 @@ void main() { final routeA = page.createRoute(context); final routeB = page.createRoute(context); - // Complete the latest route first this time. routeB.didPop('latest-result'); expect(() => routeA.didPop('stale-result'), returnsNormally); @@ -167,9 +139,6 @@ void main() { final route = page.createRoute(context); route.didPop('the-result'); - // Nothing resembling RouteNavigator's `onDidRemovePage` callback is - // ever invoked in this test, yet the router must already have been - // asked to remove the page by the time `popped` resolves. await expectLater(page.popped, completion('the-result')); expect(router.removeRouteCalls, hasLength(1)); @@ -195,12 +164,10 @@ void main() { final routeA = page.createRoute(context); final routeB = page.createRoute(context); - // The stale route popping first must not touch the router at all. routeA.didPop('stale-result'); await Future.value(); expect(router.removeRouteCalls, isEmpty); - // The latest (real) route popping removes the page exactly once. routeB.didPop('latest-result'); await expectLater(page.popped, completion('latest-result')); From 1e71dc179427cc4cd0242d700ee9124bef132f9e Mon Sep 17 00:00:00 2001 From: Eimen2018 Date: Sat, 19 Sep 2026 20:38:56 +0400 Subject: [PATCH 4/6] fix(router): remove popped page by identity Pages pushed from the same route share a routeKey, so removing by key from both the popped callback and onDidRemovePage could remove a sibling page. Remove the exact page instance instead and do nothing when it is already gone. Co-Authored-By: Claude Fable 5.1 --- .../router/controller/routing_controller.dart | 25 +++ lib/src/router/stacked_page.dart | 7 +- lib/src/router/widgets/route_navigator.dart | 8 +- test/router/remove_page_identity_test.dart | 206 ++++++++++++++++++ test/router/stacked_page_test.dart | 27 +-- 5 files changed, 256 insertions(+), 17 deletions(-) create mode 100644 test/router/remove_page_identity_test.dart diff --git a/lib/src/router/controller/routing_controller.dart b/lib/src/router/controller/routing_controller.dart index 15b6caae..f8d4cfeb 100644 --- a/lib/src/router/controller/routing_controller.dart +++ b/lib/src/router/controller/routing_controller.dart @@ -871,7 +871,13 @@ abstract class StackRouter extends RoutingController { if (pageIndex != -1) { _pages.removeAt(pageIndex); } + _finishRouteRemoval(route, notify: notify); + } + // Shared follow-up once a page has left (or was already absent from) + // `_pages`: redirect-guard cleanup, path data refresh, nested-router + // cleanup and notify. + void _finishRouteRemoval(RouteMatch route, {bool notify = true}) { final stack = _pages.map((e) => e.routeData._match); for (final guard in route.guards.whereType()) { if (!stack.any((r) => r.guards.contains(guard))) { @@ -885,6 +891,25 @@ abstract class StackRouter extends RoutingController { } } + // 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; + final route = _pages[pageIndex].routeData._match; + _pages.removeAt(pageIndex); + _finishRouteRemoval(route, notify: notify); + return true; + } + + // Runs the same cleanup as [_finishRouteRemoval] for a page that was + // already removed elsewhere, without ever removing a page by key. + @internal + void finishRemovedRouteCleanup(RouteData routeData, {bool notify = true}) { + _finishRouteRemoval(routeData._match, notify: notify); + } + @override void _onNavigate(List routes) { onNavigate?.call(routes); diff --git a/lib/src/router/stacked_page.dart b/lib/src/router/stacked_page.dart index d04c990b..0e383e96 100644 --- a/lib/src/router/stacked_page.dart +++ b/lib/src/router/stacked_page.dart @@ -73,11 +73,12 @@ abstract class StackedPage extends Page { } _popCompleter.complete(result); - // Remove the page now rather than waiting for onDidRemovePage, so the - // Navigator cannot rebuild with a stale page and recreate its route. + // 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. final router = routeData.router; if (router is StackRouter) { - router.removeRoute(routeData, notify: true); + router.removePageInstance(this); } }); return route; diff --git a/lib/src/router/widgets/route_navigator.dart b/lib/src/router/widgets/route_navigator.dart index 657d9957..6565435b 100644 --- a/lib/src/router/widgets/route_navigator.dart +++ b/lib/src/router/widgets/route_navigator.dart @@ -74,7 +74,13 @@ class RouteNavigatorState extends State { onDidRemovePage: (page) { if (page is StackedPage) { var routeData = page.routeData; - widget.router.removeRoute(routeData); + // Identity-based: a shared routeKey must not remove a + // sibling page pushed from the same route. + if (!widget.router.removePageInstance(page)) { + // Already removed elsewhere (e.g. eager removal); still + // run the same cleanup, but without removing by key. + widget.router.finishRemovedRouteCleanup(routeData); + } widget.didPop?.call(routeData.route, null); } }, diff --git a/test/router/remove_page_identity_test.dart b/test/router/remove_page_identity_test.dart new file mode 100644 index 00000000..892d7937 --- /dev/null +++ b/test/router/remove_page_identity_test.dart @@ -0,0 +1,206 @@ +// Regression tests for removing a popped/replaced page by identity rather +// than by routeKey. Two pages pushed from the same route (e.g. the same +// DetailRoute with different args) share a routeKey, so a key-based removal +// can remove the wrong (sibling) page. +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:stacked/stacked.dart'; + +class _HomeScreen extends StatelessWidget { + const _HomeScreen(); + + @override + Widget build(BuildContext context) => const Scaffold(body: Text('Home')); +} + +class _DetailScreen extends StatelessWidget { + const _DetailScreen(); + + @override + Widget build(BuildContext context) { + final id = RouteData.of(context).argsAs(); + return Scaffold(body: Text('Detail $id')); + } +} + +class _SettingsScreen extends StatelessWidget { + const _SettingsScreen(); + + @override + Widget build(BuildContext context) => const Scaffold(body: Text('Settings')); +} + +class _LoginScreen extends StatelessWidget { + const _LoginScreen(); + + @override + Widget build(BuildContext context) => const Scaffold(body: Text('Login')); +} + +class _SearchScreen extends StatelessWidget { + const _SearchScreen(); + + @override + Widget build(BuildContext context) => const Scaffold(body: Text('Search')); +} + +class _TestRouter extends RootStackRouter { + @override + late final Map pagesMap = { + 'HomeRoute': (data) => MaterialPageX( + routeData: data, + child: const _HomeScreen(), + ), + 'DetailRoute': (data) => MaterialPageX( + routeData: data, + child: const _DetailScreen(), + ), + 'SettingsRoute': (data) => MaterialPageX( + routeData: data, + child: const _SettingsScreen(), + ), + 'LoginRoute': (data) => MaterialPageX( + routeData: data, + child: const _LoginScreen(), + ), + 'SearchRoute': (data) => MaterialPageX( + routeData: data, + child: const _SearchScreen(), + ), + }; + + @override + List get routes => [ + RouteConfig('HomeRoute', path: '/', fullMatch: true), + RouteConfig('DetailRoute', path: '/detail/:id'), + RouteConfig('SettingsRoute', path: '/settings'), + RouteConfig('LoginRoute', path: '/login'), + RouteConfig('SearchRoute', path: '/search'), + ]; +} + +Future<_TestRouter> _pumpRouter( + WidgetTester tester, { + required List initialRoutes, +}) async { + final router = _TestRouter(); + await tester.pumpWidget( + MaterialApp.router( + routerDelegate: router.delegate(initialRoutes: initialRoutes), + routeInformationParser: router.defaultRouteParser(), + routeInformationProvider: router.routeInfoProvider(), + ), + ); + await tester.pumpAndSettle(); + return router; +} + +PageRouteInfo _detailRoute(int id) => PageRouteInfo( + 'DetailRoute', + path: '/detail/$id', + args: id, + rawPathParams: {'id': id}, + ); + +void main() { + testWidgets( + 'popping the top of two same-key pages only removes the top one ' + '(regression test for sibling removal by shared routeKey)', + (tester) async { + final router = await _pumpRouter( + tester, + initialRoutes: [const PageRouteInfo('HomeRoute', path: '/')], + ); + + unawaited(router.push(_detailRoute(1))); + await tester.pumpAndSettle(); + unawaited(router.push(_detailRoute(2))); + await tester.pumpAndSettle(); + + expect(router.stack, hasLength(3)); + expect(find.text('Detail 2'), findsOneWidget); + + // Both Detail pages share the default key (ValueKey('DetailRoute')). + expect(router.stack[1].routeKey, equals(router.stack[2].routeKey)); + + unawaited(router.pop()); + await tester.pumpAndSettle(); + + expect(router.stack, hasLength(2)); + expect( + router.stack.map((p) => p.routeData.name), + ['HomeRoute', 'DetailRoute'], + ); + expect(router.stack.last.routeData.args, equals(1)); + expect(find.text('Detail 1'), findsOneWidget); + expect(find.text('Detail 2'), findsNothing); + expect(find.text('Home'), findsNothing); + }, + ); + + testWidgets( + 'replacing the top of two same-key pages keeps the other one ' + '(regression test for sibling removal by shared routeKey)', + (tester) async { + final router = await _pumpRouter( + tester, + initialRoutes: [const PageRouteInfo('HomeRoute', path: '/')], + ); + + unawaited(router.push(_detailRoute(1))); + await tester.pumpAndSettle(); + unawaited(router.push(_detailRoute(2))); + await tester.pumpAndSettle(); + + expect(router.stack, hasLength(3)); + final detail1Page = router.stack[1]; + + unawaited( + router.replace(const PageRouteInfo('SettingsRoute', path: '/settings')), + ); + await tester.pumpAndSettle(); + + // Detail(1) must survive: same page instance, still holding args: 1. + // (Buried pages aren't found by `find.text` - skipOffstage treats the + // previous route's faded-out layer as offstage - so the stack itself, + // not the widget tree, is what this asserts on.) + expect( + router.stack.map((p) => p.routeData.name), + ['HomeRoute', 'DetailRoute', 'SettingsRoute'], + ); + expect(router.stack[1], same(detail1Page)); + expect(router.stack[1].routeData.args, equals(1)); + expect(find.text('Settings'), findsOneWidget); + }, + ); + + testWidgets( + 'query params set by a replace survive the disposal of the replaced page', + (tester) async { + final router = await _pumpRouter( + tester, + initialRoutes: [const PageRouteInfo('LoginRoute', path: '/login')], + ); + + expect(router.stack, hasLength(1)); + + unawaited( + router.replace( + const PageRouteInfo( + 'SearchRoute', + path: '/search', + rawQueryParams: {'q': 'x'}, + ), + ), + ); + await tester.pumpAndSettle(); + + expect(router.stack, hasLength(1)); + expect(router.stack.single.routeData.name, 'SearchRoute'); + expect(router.stack.single.routeData.queryParams.rawMap['q'], 'x'); + expect(router.currentUrl, contains('q=x')); + }, + ); +} diff --git a/test/router/stacked_page_test.dart b/test/router/stacked_page_test.dart index ee714760..981c5425 100644 --- a/test/router/stacked_page_test.dart +++ b/test/router/stacked_page_test.dart @@ -9,18 +9,19 @@ class _FakeRoutingController implements RoutingController { dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } -class _RemoveRouteCall { - const _RemoveRouteCall(this.route, {required this.notify}); - final RouteData route; +class _RemovePageInstanceCall { + const _RemovePageInstanceCall(this.page, {required this.notify}); + final StackedPage page; final bool notify; } class _FakeStackRouter implements StackRouter { - final List<_RemoveRouteCall> removeRouteCalls = []; + final List<_RemovePageInstanceCall> removePageInstanceCalls = []; @override - void removeRoute(RouteData route, {bool notify = true}) { - removeRouteCalls.add(_RemoveRouteCall(route, notify: notify)); + bool removePageInstance(StackedPage page, {bool notify = true}) { + removePageInstanceCalls.add(_RemovePageInstanceCall(page, notify: notify)); + return true; } @override @@ -141,9 +142,9 @@ void main() { await expectLater(page.popped, completion('the-result')); - expect(router.removeRouteCalls, hasLength(1)); - expect(router.removeRouteCalls.single.route, same(routeData)); - expect(router.removeRouteCalls.single.notify, isTrue); + expect(router.removePageInstanceCalls, hasLength(1)); + expect(router.removePageInstanceCalls.single.page, same(page)); + expect(router.removePageInstanceCalls.single.notify, isTrue); }, ); @@ -166,14 +167,14 @@ void main() { routeA.didPop('stale-result'); await Future.value(); - expect(router.removeRouteCalls, isEmpty); + expect(router.removePageInstanceCalls, isEmpty); routeB.didPop('latest-result'); await expectLater(page.popped, completion('latest-result')); - expect(router.removeRouteCalls, hasLength(1)); - expect(router.removeRouteCalls.single.route, same(routeData)); - expect(router.removeRouteCalls.single.notify, isTrue); + expect(router.removePageInstanceCalls, hasLength(1)); + expect(router.removePageInstanceCalls.single.page, same(page)); + expect(router.removePageInstanceCalls.single.notify, isTrue); }, ); }); From f1c31b5b83024904ecaf87c251c18124c80dce0f Mon Sep 17 00:00:00 2001 From: Fernando Ferrara Date: Tue, 22 Sep 2026 11:34:21 -0300 Subject: [PATCH 5/6] fix(router): make redirect guard removal idempotent _removeRedirectGuard used a null-check on the listener map, so any second cleanup pass for the same guard would throw. Removal cleanup must not depend on Flutter's internal ordering between onDidRemovePage and the Route.popped microtask, so tolerate a guard that was never attached or is already detached. --- lib/src/router/controller/routing_controller.dart | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/lib/src/router/controller/routing_controller.dart b/lib/src/router/controller/routing_controller.dart index f8d4cfeb..89748951 100644 --- a/lib/src/router/controller/routing_controller.dart +++ b/lib/src/router/controller/routing_controller.dart @@ -680,8 +680,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 From b06f841c703451be71c8c849aaf19b9b8f561aaa Mon Sep 17 00:00:00 2001 From: Eimen2018 Date: Wed, 23 Sep 2026 01:27:14 +0400 Subject: [PATCH 6/6] fix(router): detach child routers by page identity and keep the last page until disposal On Flutter 3.38 to 3.41 onDidRemovePage fires after the exit animation, so the eager removal in StackedPage runs first and the onDidRemovePage fallback ran the cleanup a second time. _removeTopRouterOf matched by key, so the second pass dropped the nested router of a sibling page from the same route. Child routers are now detached by page identity, the fallback only detaches what is still attached to that page, and the eager removal is skipped for the last page so the Navigator is not swapped for the placeholder mid-animation. Co-Authored-By: Claude Fable 5.1 --- .../router/controller/routing_controller.dart | 54 +++++++++---- lib/src/router/stacked_page.dart | 5 +- lib/src/router/widgets/route_navigator.dart | 6 +- test/router/nested_sibling_router_test.dart | 77 +++++++++++++++++++ test/router/stacked_page_test.dart | 28 +++++++ 5 files changed, 149 insertions(+), 21 deletions(-) create mode 100644 test/router/nested_sibling_router_test.dart diff --git a/lib/src/router/controller/routing_controller.dart b/lib/src/router/controller/routing_controller.dart index 89748951..2856f188 100644 --- a/lib/src/router/controller/routing_controller.dart +++ b/lib/src/router/controller/routing_controller.dart @@ -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; @@ -871,27 +883,30 @@ 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); } - _finishRouteRemoval(route, notify: notify); + _detachRedirectGuards(route); + _updateSharedPathData(includeAncestors: true); + if (routeData != null) { + _removeChildRouterOf(routeData, fallbackKey: route.key); + } else { + _removeTopRouterOf(route.key); + } + if (notify) { + notifyAll(forceUrlRebuild: true); + } } - // Shared follow-up once a page has left (or was already absent from) - // `_pages`: redirect-guard cleanup, path data refresh, nested-router - // cleanup and notify. - void _finishRouteRemoval(RouteMatch route, {bool notify = true}) { + void _detachRedirectGuards(RouteMatch route) { final stack = _pages.map((e) => e.routeData._match); for (final guard in route.guards.whereType()) { if (!stack.any((r) => r.guards.contains(guard))) { _removeRedirectGuard(guard); } } - _updateSharedPathData(includeAncestors: true); - _removeTopRouterOf(route.key); - if (notify) { - notifyAll(forceUrlRebuild: true); - } } // Removes [page] by identity rather than by (possibly shared) routeKey. @@ -900,17 +915,24 @@ abstract class StackRouter extends RoutingController { bool removePageInstance(StackedPage page, {bool notify = true}) { final pageIndex = _pages.indexWhere((p) => identical(p, page)); if (pageIndex == -1) return false; - final route = _pages[pageIndex].routeData._match; _pages.removeAt(pageIndex); - _finishRouteRemoval(route, notify: notify); + final route = page.routeData._match; + _detachRedirectGuards(route); + _updateSharedPathData(includeAncestors: true); + _removeChildRouterOf(page.routeData, fallbackKey: route.key); + if (notify) { + notifyAll(forceUrlRebuild: true); + } return true; } - // Runs the same cleanup as [_finishRouteRemoval] for a page that was - // already removed elsewhere, without ever removing a page by key. + // 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, {bool notify = true}) { - _finishRouteRemoval(routeData._match, notify: notify); + void finishRemovedRouteCleanup(RouteData routeData) { + _detachRedirectGuards(routeData._match); + _removeChildRouterOf(routeData); } @override diff --git a/lib/src/router/stacked_page.dart b/lib/src/router/stacked_page.dart index 0e383e96..d03a9d26 100644 --- a/lib/src/router/stacked_page.dart +++ b/lib/src/router/stacked_page.dart @@ -76,8 +76,11 @@ abstract class StackedPage extends Page { // 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) { + if (router is StackRouter && router.stack.length > 1) { router.removePageInstance(this); } }); diff --git a/lib/src/router/widgets/route_navigator.dart b/lib/src/router/widgets/route_navigator.dart index 6565435b..a9059c5f 100644 --- a/lib/src/router/widgets/route_navigator.dart +++ b/lib/src/router/widgets/route_navigator.dart @@ -74,11 +74,9 @@ class RouteNavigatorState extends State { onDidRemovePage: (page) { if (page is StackedPage) { var routeData = page.routeData; - // Identity-based: a shared routeKey must not remove a - // sibling page pushed from the same route. + // By identity: a shared routeKey must not remove a sibling + // page pushed from the same route. if (!widget.router.removePageInstance(page)) { - // Already removed elsewhere (e.g. eager removal); still - // run the same cleanup, but without removing by key. widget.router.finishRemovedRouteCleanup(routeData); } widget.didPop?.call(routeData.route, null); diff --git a/test/router/nested_sibling_router_test.dart b/test/router/nested_sibling_router_test.dart new file mode 100644 index 00000000..8ed841ec --- /dev/null +++ b/test/router/nested_sibling_router_test.dart @@ -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 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 get routes => [ + RouteConfig('HomeRoute', path: '/', fullMatch: true), + RouteConfig('DetailRoute', path: '/detail/:id', children: [ + RouteConfig('InnerRoute', path: '', fullMatch: true), + ]), + ]; +} + +PageRouteInfo _detail(int id) => PageRouteInfo( + '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); + }, + ); +} diff --git a/test/router/stacked_page_test.dart b/test/router/stacked_page_test.dart index 981c5425..69481b87 100644 --- a/test/router/stacked_page_test.dart +++ b/test/router/stacked_page_test.dart @@ -18,6 +18,9 @@ class _RemovePageInstanceCall { class _FakeStackRouter implements StackRouter { final List<_RemovePageInstanceCall> removePageInstanceCalls = []; + @override + List stack = []; + @override bool removePageInstance(StackedPage page, {bool notify = true}) { removePageInstanceCalls.add(_RemovePageInstanceCall(page, notify: notify)); @@ -136,6 +139,7 @@ void main() { routeData: routeData, child: const SizedBox(), ); + router.stack = [page, page]; final route = page.createRoute(context); route.didPop('the-result'); @@ -148,6 +152,29 @@ void main() { }, ); + testWidgets( + 'popping the last page does not eagerly remove it, so the Navigator ' + 'stays mounted during the exit animation', + (WidgetTester tester) async { + await tester.pumpWidget(const MaterialApp(home: SizedBox())); + final context = tester.element(find.byType(SizedBox)); + + final router = _FakeStackRouter(); + final routeData = _buildRouteData('last-page', router: router); + final page = _TestPage( + routeData: routeData, + child: const SizedBox(), + ); + router.stack = [page]; + + final route = page.createRoute(context); + route.didPop('the-result'); + + await expectLater(page.popped, completion('the-result')); + expect(router.removePageInstanceCalls, isEmpty); + }, + ); + testWidgets( 'createRoute called twice only removes the page from the router once, ' 'for the latest route, and not for the stale one', @@ -161,6 +188,7 @@ void main() { routeData: routeData, child: const SizedBox(), ); + router.stack = [page, page]; final routeA = page.createRoute(context); final routeB = page.createRoute(context);