Skip to content

Commit 3c7764b

Browse files
authored
[go_router] Stop inactive StatefulShellRoute branches from vetoing pops (#12972)
The Navigator of every StatefulShellRoute branch is wrapped in a PopScope that keeps the shell itself from being popped, for example by an iOS back gesture, while the branch has an active sub-route. Inactive branches stay mounted, so their PopScope stays registered as a pop entry of the same enclosing route as the active one, and ModalRoute only allows a pop if every registered entry allows it. Switching away from a branch that still had a sub-route therefore suppressed the system back button for the whole app: popRoute() reported the pop as handled without popping anything, so Android never closed the activity. The guard now only applies to the active branch. StatefulNavigationShell publishes which of its branches is active through an ActiveBranchScope inherited widget, and the PopScope depends on it, so canPop is also kept up to date when the user switches branches without the route matches of a branch changing. Behavior is unchanged for a plain ShellRoute, which has no enclosing ActiveBranchScope. Tests added to `test/stateful_shell_route_system_back_test.dart`, next to the existing issue 120353 gesture tests: the issue's repro, back still popping the sub-route once the branch is active again, and a per-branch `canPop` check confirming the active branch still guards the shell. Also verified manually on an Android 15 device. Fixes flutter/flutter#193098 *Replace this paragraph with a description of what this PR is changing or adding, and why. Consider including before/after screenshots.* *List which issues are fixed by this PR. You must list at least one issue.* ## Pre-Review Checklist **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed. [^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 10edd9c commit 3c7764b

5 files changed

Lines changed: 345 additions & 28 deletions

File tree

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

Lines changed: 40 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import 'package:flutter/widgets.dart';
77
import 'configuration.dart';
88
import 'logging.dart';
99
import 'match.dart';
10+
import 'misc/active_branch_scope.dart';
1011
import 'misc/error_screen.dart';
1112
import 'misc/errors.dart';
1213
import 'pages/cupertino.dart';
@@ -336,30 +337,45 @@ class _CustomNavigatorState extends State<_CustomNavigator> {
336337
List<NavigatorObserver>? observers,
337338
String? restorationScopeId,
338339
) {
339-
return PopScope(
340-
// Prevent ShellRoute from being popped, for example
341-
// by an iOS back gesture, when the route has active sub-routes.
342-
// TODO(LukasMirbt): Remove when minimum flutter version includes
343-
// https://github.com/flutter/flutter/pull/152330.
344-
canPop: match.matches.length == 1,
345-
child: _CustomNavigator(
346-
// The state needs to persist across rebuild.
347-
key: ValueKey<GlobalKey<NavigatorState>>(navigatorKey),
348-
navigatorRestorationId: restorationScopeId,
349-
navigatorKey: navigatorKey,
350-
matches: match.matches,
351-
matchList: matchList,
352-
inheritedMetadata: state.metadata,
353-
configuration: widget.configuration,
354-
observers: observers ?? const <NavigatorObserver>[],
355-
onPopPageWithRouteMatch: widget.onPopPageWithRouteMatch,
356-
// This is used to recursively build pages under this shell route.
357-
errorBuilder: widget.errorBuilder,
358-
errorPageBuilder: widget.errorPageBuilder,
359-
requestFocus: widget.requestFocus,
360-
isShellNavigator: true,
361-
clipBehavior: _clipBehaviorFor(match.route, navigatorKey),
362-
),
340+
final Widget navigator = _CustomNavigator(
341+
// The state needs to persist across rebuild.
342+
key: ValueKey<GlobalKey<NavigatorState>>(navigatorKey),
343+
navigatorRestorationId: restorationScopeId,
344+
navigatorKey: navigatorKey,
345+
matches: match.matches,
346+
matchList: matchList,
347+
inheritedMetadata: state.metadata,
348+
configuration: widget.configuration,
349+
observers: observers ?? const <NavigatorObserver>[],
350+
onPopPageWithRouteMatch: widget.onPopPageWithRouteMatch,
351+
// This is used to recursively build pages under this shell route.
352+
errorBuilder: widget.errorBuilder,
353+
errorPageBuilder: widget.errorPageBuilder,
354+
requestFocus: widget.requestFocus,
355+
isShellNavigator: true,
356+
clipBehavior: _clipBehaviorFor(match.route, navigatorKey),
357+
);
358+
// The Builder gives the PopScope a context below the
359+
// ActiveBranchScope of the branch this Navigator belongs to, so
360+
// that canPop is kept up to date when the active branch changes.
361+
return Builder(
362+
builder: (BuildContext context) {
363+
return PopScope(
364+
// Prevent ShellRoute from being popped, for example
365+
// by an iOS back gesture, when the route has active
366+
// sub-routes.
367+
//
368+
// Inactive StatefulShellRoute branches stay mounted, and
369+
// their PopScope is registered on the same enclosing route
370+
// as the one of the active branch. Since a single doNotPop
371+
// vote suppresses the pop for all of them, only the active
372+
// branch may hold back a pop.
373+
// TODO(LukasMirbt): Remove when minimum flutter version includes
374+
// https://github.com/flutter/flutter/pull/152330.
375+
canPop: match.matches.length == 1 || !ActiveBranchScope.isActiveBranchOf(context),
376+
child: navigator,
377+
);
378+
},
363379
);
364380
},
365381
);
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Copyright 2013 The Flutter Authors
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import 'package:flutter/widgets.dart';
6+
import 'package:meta/meta.dart';
7+
8+
/// Marks whether the subtree below it belongs to the currently active branch
9+
/// of a `StatefulShellRoute`.
10+
///
11+
/// Every branch of a `StatefulShellRoute` stays mounted, including the
12+
/// inactive ones. Widgets that must only take effect for the branch the user
13+
/// is currently looking at can use [isActiveBranchOf] to find out whether they
14+
/// are part of the active branch.
15+
@internal
16+
class ActiveBranchScope extends InheritedWidget {
17+
/// Constructs an [ActiveBranchScope].
18+
const ActiveBranchScope({required this.isActive, required super.child, super.key});
19+
20+
/// Whether the subtree below this widget belongs to the active branch of the
21+
/// enclosing `StatefulShellRoute`.
22+
final bool isActive;
23+
24+
/// Whether [context] is part of the active branch of the closest enclosing
25+
/// `StatefulShellRoute`.
26+
///
27+
/// Returns true when [context] is not below a `StatefulShellRoute`, for
28+
/// instance for the [Navigator] of a plain `ShellRoute`.
29+
///
30+
/// The calling widget is rebuilt whenever the active branch changes.
31+
static bool isActiveBranchOf(BuildContext context) =>
32+
context.dependOnInheritedWidgetOfExactType<ActiveBranchScope>()?.isActive ?? true;
33+
34+
@override
35+
bool updateShouldNotify(ActiveBranchScope oldWidget) => isActive != oldWidget.isActive;
36+
}

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

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import 'package:meta/meta.dart' as meta;
1515

1616
import 'configuration.dart';
1717
import 'match.dart';
18+
import 'misc/active_branch_scope.dart';
1819
import 'path_utils.dart';
1920
import 'router.dart';
2021
import 'state.dart';
@@ -1635,13 +1636,17 @@ class StatefulNavigationShellState extends State<StatefulNavigationShell> with R
16351636

16361637
@override
16371638
Widget build(BuildContext context) {
1639+
// A nested StatefulShellRoute is only active if the branch hosting it is
1640+
// active as well.
1641+
final bool isActiveShell = ActiveBranchScope.isActiveBranchOf(context);
16381642
final List<Widget> children = route.branches
1639-
.map(
1640-
(StatefulShellBranch branch) => _BranchNavigatorProxy(
1643+
.mapIndexed(
1644+
(int index, StatefulShellBranch branch) => _BranchNavigatorProxy(
16411645
key: ValueKey<GlobalKey<NavigatorState>>(branch.navigatorKey),
16421646
branch: branch,
16431647
navigatorForBranch: (StatefulShellBranch branch) =>
16441648
_branchState[branch.navigatorKey]?.navigator,
1649+
isActive: isActiveShell && index == currentIndex,
16451650
),
16461651
)
16471652
.toList();
@@ -1712,11 +1717,19 @@ typedef _NavigatorForBranch = Widget? Function(StatefulShellBranch);
17121717
/// important for container implementations that cache child widgets,
17131718
/// such as [TabBarView].
17141719
class _BranchNavigatorProxy extends StatefulWidget {
1715-
const _BranchNavigatorProxy({super.key, required this.branch, required this.navigatorForBranch});
1720+
const _BranchNavigatorProxy({
1721+
super.key,
1722+
required this.branch,
1723+
required this.navigatorForBranch,
1724+
required this.isActive,
1725+
});
17161726

17171727
final StatefulShellBranch branch;
17181728
final _NavigatorForBranch navigatorForBranch;
17191729

1730+
/// Whether [branch] is the currently active branch.
1731+
final bool isActive;
1732+
17201733
@override
17211734
State<StatefulWidget> createState() => _BranchNavigatorProxyState();
17221735
}
@@ -1729,7 +1742,10 @@ class _BranchNavigatorProxyState extends State<_BranchNavigatorProxy>
17291742
@override
17301743
Widget build(BuildContext context) {
17311744
super.build(context);
1732-
return widget.navigatorForBranch(widget.branch) ?? const SizedBox.shrink();
1745+
return ActiveBranchScope(
1746+
isActive: widget.isActive,
1747+
child: widget.navigatorForBranch(widget.branch) ?? const SizedBox.shrink(),
1748+
);
17331749
}
17341750

17351751
@override
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
changelog: |
2+
- Fixes the system back button being ignored after switching away from a `StatefulShellRoute` branch that still has an active sub-route.
3+
version: patch

0 commit comments

Comments
 (0)