Skip to content

Commit 01aa7fc

Browse files
committed
[go_router] Stop inactive StatefulShellRoute branches from vetoing pops
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. Fixes flutter/flutter#193098
1 parent 8bfc0c2 commit 01aa7fc

5 files changed

Lines changed: 263 additions & 27 deletions

File tree

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

Lines changed: 39 additions & 23 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';
@@ -308,29 +309,44 @@ class _CustomNavigatorState extends State<_CustomNavigator> {
308309
List<NavigatorObserver>? observers,
309310
String? restorationScopeId,
310311
) {
311-
return PopScope(
312-
// Prevent ShellRoute from being popped, for example
313-
// by an iOS back gesture, when the route has active sub-routes.
314-
// TODO(LukasMirbt): Remove when minimum flutter version includes
315-
// https://github.com/flutter/flutter/pull/152330.
316-
canPop: match.matches.length == 1,
317-
child: _CustomNavigator(
318-
// The state needs to persist across rebuild.
319-
key: GlobalObjectKey(navigatorKey.hashCode),
320-
navigatorRestorationId: restorationScopeId,
321-
navigatorKey: navigatorKey,
322-
matches: match.matches,
323-
matchList: matchList,
324-
inheritedMetadata: state.metadata,
325-
configuration: widget.configuration,
326-
observers: observers ?? const <NavigatorObserver>[],
327-
onPopPageWithRouteMatch: widget.onPopPageWithRouteMatch,
328-
// This is used to recursively build pages under this shell route.
329-
errorBuilder: widget.errorBuilder,
330-
errorPageBuilder: widget.errorPageBuilder,
331-
requestFocus: widget.requestFocus,
332-
isShellNavigator: true,
333-
),
312+
final Widget navigator = _CustomNavigator(
313+
// The state needs to persist across rebuild.
314+
key: GlobalObjectKey(navigatorKey.hashCode),
315+
navigatorRestorationId: restorationScopeId,
316+
navigatorKey: navigatorKey,
317+
matches: match.matches,
318+
matchList: matchList,
319+
inheritedMetadata: state.metadata,
320+
configuration: widget.configuration,
321+
observers: observers ?? const <NavigatorObserver>[],
322+
onPopPageWithRouteMatch: widget.onPopPageWithRouteMatch,
323+
// This is used to recursively build pages under this shell route.
324+
errorBuilder: widget.errorBuilder,
325+
errorPageBuilder: widget.errorPageBuilder,
326+
requestFocus: widget.requestFocus,
327+
isShellNavigator: true,
328+
);
329+
// The Builder gives the PopScope a context below the
330+
// ActiveBranchScope of the branch this Navigator belongs to, so
331+
// that canPop is kept up to date when the active branch changes.
332+
return Builder(
333+
builder: (BuildContext context) {
334+
return PopScope(
335+
// Prevent ShellRoute from being popped, for example
336+
// by an iOS back gesture, when the route has active
337+
// sub-routes.
338+
//
339+
// Inactive StatefulShellRoute branches stay mounted, and
340+
// their PopScope is registered on the same enclosing route
341+
// as the one of the active branch. Since a single doNotPop
342+
// vote suppresses the pop for all of them, only the active
343+
// branch may hold back a pop.
344+
// TODO(LukasMirbt): Remove when minimum flutter version includes
345+
// https://github.com/flutter/flutter/pull/152330.
346+
canPop: match.matches.length == 1 || !ActiveBranchScope.isActiveBranchOf(context),
347+
child: navigator,
348+
);
349+
},
334350
);
335351
},
336352
);
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
7+
/// Marks whether the subtree below it belongs to the currently active branch
8+
/// of a `StatefulShellRoute`.
9+
///
10+
/// Every branch of a `StatefulShellRoute` stays mounted, including the
11+
/// inactive ones. Widgets that must only take effect for the branch the user
12+
/// is currently looking at can use [isActiveBranchOf] to find out whether they
13+
/// are part of the active branch.
14+
class ActiveBranchScope extends InheritedWidget {
15+
/// Constructs an [ActiveBranchScope].
16+
const ActiveBranchScope({required this.isActive, required super.child, super.key});
17+
18+
/// Whether the subtree below this widget belongs to the active branch of the
19+
/// enclosing `StatefulShellRoute`.
20+
final bool isActive;
21+
22+
/// Whether [context] is part of the active branch of the closest enclosing
23+
/// `StatefulShellRoute`.
24+
///
25+
/// Returns true when [context] is not below a `StatefulShellRoute`, for
26+
/// instance for the [Navigator] of a plain `ShellRoute`.
27+
///
28+
/// The calling widget is rebuilt whenever the active branch changes.
29+
static bool isActiveBranchOf(BuildContext context) =>
30+
context.dependOnInheritedWidgetOfExactType<ActiveBranchScope>()?.isActive ?? true;
31+
32+
@override
33+
bool updateShouldNotify(ActiveBranchScope oldWidget) => isActive != oldWidget.isActive;
34+
}

‎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';
@@ -1506,12 +1507,16 @@ class StatefulNavigationShellState extends State<StatefulNavigationShell> with R
15061507

15071508
@override
15081509
Widget build(BuildContext context) {
1510+
// A nested StatefulShellRoute is only active if the branch hosting it is
1511+
// active as well.
1512+
final bool isActiveShell = ActiveBranchScope.isActiveBranchOf(context);
15091513
final List<Widget> children = route.branches
1510-
.map(
1511-
(StatefulShellBranch branch) => _BranchNavigatorProxy(
1514+
.mapIndexed(
1515+
(int index, StatefulShellBranch branch) => _BranchNavigatorProxy(
15121516
key: ObjectKey(branch),
15131517
branch: branch,
15141518
navigatorForBranch: (StatefulShellBranch branch) => _branchState[branch]?.navigator,
1519+
isActive: isActiveShell && index == currentIndex,
15151520
),
15161521
)
15171522
.toList();
@@ -1582,11 +1587,19 @@ typedef _NavigatorForBranch = Widget? Function(StatefulShellBranch);
15821587
/// important for container implementations that cache child widgets,
15831588
/// such as [TabBarView].
15841589
class _BranchNavigatorProxy extends StatefulWidget {
1585-
const _BranchNavigatorProxy({super.key, required this.branch, required this.navigatorForBranch});
1590+
const _BranchNavigatorProxy({
1591+
super.key,
1592+
required this.branch,
1593+
required this.navigatorForBranch,
1594+
required this.isActive,
1595+
});
15861596

15871597
final StatefulShellBranch branch;
15881598
final _NavigatorForBranch navigatorForBranch;
15891599

1600+
/// Whether [branch] is the currently active branch.
1601+
final bool isActive;
1602+
15901603
@override
15911604
State<StatefulWidget> createState() => _BranchNavigatorProxyState();
15921605
}
@@ -1599,7 +1612,10 @@ class _BranchNavigatorProxyState extends State<_BranchNavigatorProxy>
15991612
@override
16001613
Widget build(BuildContext context) {
16011614
super.build(context);
1602-
return widget.navigatorForBranch(widget.branch) ?? const SizedBox.shrink();
1615+
return ActiveBranchScope(
1616+
isActive: widget.isActive,
1617+
child: widget.navigatorForBranch(widget.branch) ?? const SizedBox.shrink(),
1618+
);
16031619
}
16041620

16051621
@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

‎packages/go_router/test/stateful_shell_route_system_back_test.dart‎

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,89 @@ void main() {
8888
expect(find.text('Home'), findsOneWidget);
8989
});
9090
});
91+
92+
// Regression test for https://github.com/flutter/flutter/issues/193098
93+
group('Inactive StatefulShellRoute branch with an active sub-route', () {
94+
testWidgets('does not prevent the root route from being popped', (WidgetTester tester) async {
95+
await tester.pumpWidget(const _MultiBranchTestApp());
96+
expect(find.text('Home'), findsOneWidget);
97+
98+
await tester.tap(find.byKey(const Key('toSettings')));
99+
await tester.pumpAndSettle();
100+
expect(find.text('Settings'), findsOneWidget);
101+
102+
await tester.tap(find.byKey(const Key('toGeneral')));
103+
await tester.pumpAndSettle();
104+
expect(find.text('General'), findsOneWidget);
105+
106+
// Leave the Settings branch without popping its sub-route first.
107+
await tester.tap(find.byKey(const Key('toHome')));
108+
await tester.pumpAndSettle();
109+
expect(find.text('Home'), findsOneWidget);
110+
111+
// The Home branch has nothing to pop, so the system back must not be
112+
// handled by the framework, allowing the platform to close the app.
113+
expect(await tester.binding.handlePopRoute(), isFalse);
114+
});
115+
116+
testWidgets('keeps popping its sub-route once the branch is active again', (
117+
WidgetTester tester,
118+
) async {
119+
await tester.pumpWidget(const _MultiBranchTestApp());
120+
121+
await tester.tap(find.byKey(const Key('toSettings')));
122+
await tester.pumpAndSettle();
123+
await tester.tap(find.byKey(const Key('toGeneral')));
124+
await tester.pumpAndSettle();
125+
await tester.tap(find.byKey(const Key('toHome')));
126+
await tester.pumpAndSettle();
127+
128+
await tester.tap(find.byKey(const Key('toSettings')));
129+
await tester.pumpAndSettle();
130+
expect(find.text('General'), findsOneWidget);
131+
132+
expect(await tester.binding.handlePopRoute(), isTrue);
133+
await tester.pumpAndSettle();
134+
expect(find.text('Settings'), findsOneWidget);
135+
136+
// The Settings branch no longer has a sub-route, so back is unhandled.
137+
expect(await tester.binding.handlePopRoute(), isFalse);
138+
});
139+
140+
testWidgets('only the active branch guards against popping the shell', (
141+
WidgetTester tester,
142+
) async {
143+
await tester.pumpWidget(const _MultiBranchTestApp());
144+
// Only the Navigator of the initial branch has been created so far.
145+
expect(_branchCanPopValues(tester), <bool>[true]);
146+
147+
await tester.tap(find.byKey(const Key('toSettings')));
148+
await tester.pumpAndSettle();
149+
await tester.tap(find.byKey(const Key('toGeneral')));
150+
await tester.pumpAndSettle();
151+
152+
// The active Settings branch has a sub-route, so the shell itself must
153+
// stay protected against being popped, for example by an iOS back
154+
// gesture.
155+
expect(_branchCanPopValues(tester), <bool>[true, false]);
156+
157+
await tester.tap(find.byKey(const Key('toHome')));
158+
await tester.pumpAndSettle();
159+
160+
// Settings is now inactive and must no longer veto pops, even though it
161+
// still has an active sub-route.
162+
expect(_branchCanPopValues(tester), <bool>[true, true]);
163+
});
164+
});
91165
}
92166

167+
/// The `canPop` value of the [PopScope] wrapping each branch Navigator, in
168+
/// branch order.
169+
List<bool> _branchCanPopValues(WidgetTester tester) => tester
170+
.widgetList(find.byWidgetPredicate((Widget widget) => widget is PopScope, skipOffstage: false))
171+
.map((Widget widget) => (widget as PopScope<dynamic>).canPop)
172+
.toList();
173+
93174
class _TestApp extends StatefulWidget {
94175
const _TestApp();
95176

@@ -172,3 +253,89 @@ class _TestAppState extends State<_TestApp> {
172253
return MaterialApp.router(routerConfig: _router);
173254
}
174255
}
256+
257+
class _MultiBranchTestApp extends StatefulWidget {
258+
const _MultiBranchTestApp();
259+
260+
@override
261+
State<_MultiBranchTestApp> createState() => _MultiBranchTestAppState();
262+
}
263+
264+
class _MultiBranchTestAppState extends State<_MultiBranchTestApp> {
265+
final GoRouter _router = GoRouter(
266+
initialLocation: '/home',
267+
routes: <RouteBase>[
268+
StatefulShellRoute.indexedStack(
269+
builder:
270+
(BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) {
271+
return Scaffold(
272+
body: navigationShell,
273+
bottomNavigationBar: Row(
274+
children: <Widget>[
275+
FilledButton(
276+
key: const Key('toHome'),
277+
onPressed: () => navigationShell.goBranch(0),
278+
child: const Text('To Home'),
279+
),
280+
FilledButton(
281+
key: const Key('toSettings'),
282+
onPressed: () => navigationShell.goBranch(1),
283+
child: const Text('To Settings'),
284+
),
285+
],
286+
),
287+
);
288+
},
289+
branches: <StatefulShellBranch>[
290+
StatefulShellBranch(
291+
routes: <RouteBase>[
292+
GoRoute(
293+
path: '/home',
294+
builder: (BuildContext context, GoRouterState state) {
295+
return const Scaffold(body: Center(child: Text('Home')));
296+
},
297+
),
298+
],
299+
),
300+
StatefulShellBranch(
301+
routes: <RouteBase>[
302+
GoRoute(
303+
path: '/settings',
304+
builder: (BuildContext context, GoRouterState state) {
305+
return Scaffold(
306+
body: Center(
307+
child: FilledButton(
308+
key: const Key('toGeneral'),
309+
onPressed: () => GoRouter.of(context).go('/settings/general'),
310+
child: const Text('Settings'),
311+
),
312+
),
313+
);
314+
},
315+
routes: <RouteBase>[
316+
GoRoute(
317+
path: 'general',
318+
builder: (BuildContext context, GoRouterState state) {
319+
return const Scaffold(body: Center(child: Text('General')));
320+
},
321+
),
322+
],
323+
),
324+
],
325+
),
326+
],
327+
),
328+
],
329+
);
330+
331+
@override
332+
void dispose() {
333+
_router.dispose();
334+
super.dispose();
335+
}
336+
337+
@override
338+
Widget build(BuildContext context) {
339+
return MaterialApp.router(routerConfig: _router);
340+
}
341+
}

0 commit comments

Comments
 (0)