Skip to content
20 changes: 18 additions & 2 deletions lib/src/router/controller/routing_controller.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import 'dart:async';
import 'package:collection/collection.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:stacked/src/code_generation/router_annotation/parameters.dart';
import 'package:stacked/src/router/controller/controller_scope.dart';
import 'package:stacked/src/router/controller/navigation_history/navigation_history_base.dart';
Expand Down Expand Up @@ -868,9 +869,11 @@ abstract class StackRouter extends RoutingController {

void _removeRoute(RouteMatch route, {bool notify = true}) {
var pageIndex = _pages.lastIndexWhere((p) => p.routeKey == route.key);
if (pageIndex != -1) {
_pages.removeAt(pageIndex);
if (pageIndex == -1) {
// Already removed by another path; nothing to notify.
return;

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.

Early return skips the redirect-guard cleanup and child-router cleanup when the page is already gone from _pages.

removeWhere (and _reset / updateDeclarativeRoutes) take pages out of _pages directly. They never call _removeRedirectGuard or _removeTopRouterOf. Before this PR, when the Navigator then dropped that page, onDidRemovePage -> removeRoute hit pageIndex == -1 but still ran the guard loop and _removeTopRouterOf, so the listener got cleaned up there. With this early return that never happens.

Scenario: a route guarded by a RedirectGuard is removed with router.removeWhere(...). Its listener stays in _redirectGuardsListeners. The next time the guard calls notifyListeners() (for example on an auth state change), _reevaluate runs on this router. No guarded route is left in the stack, so it goes straight to _strategy.reevaluate(...), and that can re-push routes or removeAllAndPush for a page the user already left.

Suggestion: skip only the _pages.removeAt and the notification when pageIndex == -1. Keep the cleanup, but make it null-safe. For example, _removeRedirectGuard should do nothing if _redirectGuardsListeners[guard] is null.

}
_pages.removeAt(pageIndex);

final stack = _pages.map((e) => e.routeData._match);
for (final guard in route.guards.whereType<RedirectGuard>()) {
Expand All @@ -881,6 +884,19 @@ abstract class StackRouter extends RoutingController {
_updateSharedPathData(includeAncestors: true);
_removeTopRouterOf(route.key);
if (notify) {
_notifyRouteRemoved();
}
}

// Defers the notification when called mid-build to avoid setState during
// build.
void _notifyRouteRemoved() {

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.

[medium] The build-phase guard is applied only to _removeRoute, so the reported crash is still reachable through the sibling removal paths.

notifyAll(forceUrlRebuild: true) is also called synchronously from removeWhere (~line 1089) and _removeUntil (~line 1075), and notifyAll() from _addEntry (~line 1181). None of them go through _notifyRouteRemoved, so they still call setState()/markNeedsBuild() during build.

I verified this on this branch: a descendant widget whose build calls router.removeWhere((r) => r.name == 'SecondRoute') (the same shape as the first new test, which uses removeRoute) still throws:

The following assertion was thrown while dispatching notifications for _R:
setState() or markNeedsBuild() called during build.
The widget on which setState() or markNeedsBuild() was called was: _RootRouter
...
The following assertion was thrown while dispatching notifications for NestedRouterDelegate:
setState() or markNeedsBuild() called during build.
The widget on which setState() or markNeedsBuild() was called was: Router<Object>

Note this also shows the second setState source (NestedRouterDelegate._handleRebuild via navigationHistory.rebuildUrl()), which _notifyRouteRemoved happens to cover for the _removeRoute path but not elsewhere.

Since the helper already exists, consider making it a general _notifySafely({bool forceUrlRebuild}) and routing removeWhere, _removeUntil and _addEntry through it too — otherwise the fix is specific to the one stack frame in #1184 rather than to the class of bug.

if (SchedulerBinding.instance.schedulerPhase ==
SchedulerPhase.persistentCallbacks) {
SchedulerBinding.instance.addPostFrameCallback((_) {
notifyAll(forceUrlRebuild: true);

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 deferred notifyAll can run on a router that has already been disposed.

The post-frame closure holds onto this and never checks whether the controller is still alive. Nested routers dispose their StackRouter in State.dispose (nested_router.dart, nested_router_delegate.dart). Unmounting happens during finalizeTree, which is still in the same persistentCallbacks phase that scheduled the callback.

Scenario: a nested router gets onDidRemovePage during the build phase, and its widget is unmounted later in that same frame. The post-frame callback then calls notifyListeners() on the disposed ChangeNotifier. In debug builds this throws "A StackRouter was used after being disposed". It also still triggers root.notifyListeners() and navigationHistory.rebuildUrl() from a stale router, which can overwrite the URL with the torn-down state.

Suggestion: track disposal (for example a _disposed flag set in dispose) and return early from the callback when it is set.

});
} else {
notifyAll(forceUrlRebuild: true);
}
}
Expand Down
145 changes: 145 additions & 0 deletions test/router/browser_back_navigation_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import 'dart:async';

import 'package:flutter/foundation.dart';
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 _SecondScreen extends StatelessWidget {
const _SecondScreen({required this.router, required this.triggerRemoval});

final StackRouter router;
final ValueListenable<bool> triggerRemoval;

@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: Listenable.merge([router, triggerRemoval]),
builder: (context, _) {
if (triggerRemoval.value) {
final topPage = router.stack.last;
if (topPage.routeKey == const ValueKey('SecondRoute')) {
router.removeRoute(topPage.routeData);
}
}
return const Scaffold(body: Text('Second'));
},
);
}
}

class _TestRouter extends RootStackRouter {
_TestRouter(this.triggerRemoval);

final ValueListenable<bool> triggerRemoval;

@override
late final Map<String, PageFactory> pagesMap = {
'HomeRoute': (data) => MaterialPageX(
routeData: data,
child: const _HomeScreen(),
),
'SecondRoute': (data) => MaterialPageX(
routeData: data,
child: _SecondScreen(router: this, triggerRemoval: triggerRemoval),
),
};

@override
List<RouteConfig> get routes => [
RouteConfig('HomeRoute', path: '/', fullMatch: true),
RouteConfig('SecondRoute', path: '/second', fullMatch: true),
];
}

void main() {
testWidgets(
'removing the current top page from a descendant rebuilt while the '
'router widget is itself rebuilding does not throw "setState() called '
'during build"',
(tester) async {
final triggerRemoval = ValueNotifier<bool>(false);
final router = _TestRouter(triggerRemoval);
addTearDown(triggerRemoval.dispose);

await tester.pumpWidget(
MaterialApp.router(
routerDelegate: router.delegate(
initialRoutes: [
const PageRouteInfo('HomeRoute', path: '/'),
],
),
routeInformationParser: router.defaultRouteParser(),
routeInformationProvider: router.routeInfoProvider(),
),
);
await tester.pumpAndSettle();

expect(find.text('Home'), findsOneWidget);

unawaited(
router.push(const PageRouteInfo('SecondRoute', path: '/second')),
);
await tester.pumpAndSettle();

expect(find.text('Second'), findsOneWidget);
expect(router.stack, hasLength(2));

triggerRemoval.value = true;
router.notifyListeners();
await tester.pump();

expect(tester.takeException(), isNull);

await tester.pumpAndSettle();
expect(tester.takeException(), isNull);

expect(find.text('Home'), findsOneWidget);
expect(find.text('Second'), findsNothing);
expect(router.stack, hasLength(1));
},
);

testWidgets(
'a real system/browser back navigation does not throw '
'"setState() called during build"',
(tester) async {
final triggerRemoval = ValueNotifier<bool>(false);
final router = _TestRouter(triggerRemoval);
addTearDown(triggerRemoval.dispose);

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(const PageRouteInfo('SecondRoute', path: '/second')),
);
await tester.pumpAndSettle();
expect(find.text('Second'), findsOneWidget);

await tester.binding.handlePopRoute();

for (var i = 0; i < 10; i++) {
await tester.pump(const Duration(milliseconds: 50));
expect(tester.takeException(), isNull);
}

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.

[low] This second test passes on master too, so it does not guard the fix — and it never asserts that the back navigation actually did anything.

I ran the three new test files against the pre-fix routing_controller.dart: browser_back_navigation_test.dart test #1 and nested_router_dispose_test.dart fail (good reproductions), but this handlePopRoute() test passes both before and after. So the "real system/browser back navigation" path as modelled here never actually hit the reported exception.

It is also vacuous in a second way: the only assertion is takeException() == null. If handlePopRoute() silently did nothing, the test would still pass. Instrumenting it shows the pop does happen (router.stack.length == 1, currentUrl == '/'), so those are cheap assertions to add:

Suggested change
await tester.binding.handlePopRoute();
for (var i = 0; i < 10; i++) {
await tester.pump(const Duration(milliseconds: 50));
expect(tester.takeException(), isNull);
}
await tester.binding.handlePopRoute();
for (var i = 0; i < 10; i++) {
await tester.pump(const Duration(milliseconds: 50));
expect(tester.takeException(), isNull);
}
expect(router.stack, hasLength(1));
expect(find.text('Home'), findsOneWidget);
expect(router.currentUrl, '/');

Worth flagging in the PR description too, since it is presented as the end-to-end check for #1184 — the only test that actually reproduces the reported exception is test #1, which triggers the removal from a descendant's build rather than from a genuine browser back.

},
);
}
Loading