Require double back to exit Android tab roots

This commit is contained in:
2026-10-24 02:23:15 +01:00
parent 54f74ade33
commit 4e6771aa24
6 changed files with 233 additions and 11 deletions
@@ -0,0 +1,63 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
/// A short, Android-only exit window. The second Back is left to the platform,
/// including its predictive back-to-home animation, rather than forcing exit.
class AndroidRootExit extends NavigatorObserver {
AndroidRootExit(this.onChanged);
final VoidCallback onChanged;
static const window = Duration(seconds: 2);
Timer? _timer;
ScaffoldFeatureController<SnackBar, SnackBarClosedReason>? _hint;
bool _disposed = false;
bool get enabled =>
!kIsWeb && defaultTargetPlatform == TargetPlatform.android;
bool get armed => _timer?.isActive ?? false;
bool handleBack() {
if (!enabled || armed) return false;
_timer = Timer(window, () {
_timer = null;
onChanged();
});
final context = navigator?.context;
if (context != null) {
_hint = ScaffoldMessenger.maybeOf(context)?.showSnackBar(
const SnackBar(
content: Text('Press back again to close'),
duration: window,
),
);
}
onChanged();
return true;
}
void clear() {
_timer?.cancel();
_timer = null;
_hint?.close();
_hint = null;
}
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
if (previousRoute == null || !armed) return;
// Dialogs and imperative detail routes do not change the URL. Invalidate
// their exit window too, outside the Navigator's build/route flush.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_disposed) return;
clear();
onChanged();
});
}
void dispose() {
_disposed = true;
_timer?.cancel();
}
}
+30 -3
View File
@@ -1,6 +1,7 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'android_root_exit.dart';
import 'app_route.dart';
/// Parses the browser (or platform) location into the app's routes.
@@ -83,6 +84,7 @@ class AppRouterDelegate extends RouterDelegate<AppRoute> with ChangeNotifier {
final bool cupertino;
final _navigatorKey = GlobalKey<NavigatorState>();
late final _rootExit = AndroidRootExit(notifyListeners);
static const _pageKey = ValueKey<String>('pipelines-shell');
static const _searchPageKey = ValueKey<String>('app-search');
static const _templatesPageKey = ValueKey<String>('app-templates');
@@ -142,6 +144,7 @@ class AppRouterDelegate extends RouterDelegate<AppRoute> with ChangeNotifier {
: _route;
return Navigator(
key: _navigatorKey,
observers: [_rootExit],
pages: [
// While an item is open inside its tab (a wide screen keeps it
// there), Android's Back and back gesture step up a level instead of
@@ -149,9 +152,11 @@ class AppRouterDelegate extends RouterDelegate<AppRoute> with ChangeNotifier {
_page(
_pageKey,
PopScope(
canPop: !_canStepUp,
canPop: !_canStepUp && !(_isExitRoot && !_rootExit.armed),
onPopInvokedWithResult: (didPop, _) {
if (!didPop) _stepUp();
if (!didPop && !_stepUp() && _isExitRoot) {
_rootExit.handleBack();
}
},
child: builder(context, shellRoute),
),
@@ -214,19 +219,22 @@ class AppRouterDelegate extends RouterDelegate<AppRoute> with ChangeNotifier {
@override
Future<void> setInitialRoutePath(AppRoute configuration) async {
_rootExit.clear();
_route = configuration;
}
@override
Future<void> setNewRoutePath(AppRoute configuration) async {
if (configuration == _route) return;
_rootExit.clear();
_route = configuration;
notifyListeners();
}
/// Back (Android's button, the browser's): close whatever page sits on top
/// first, then step up one level — a stage to its run or pipeline, a run,
/// pipeline or chat to its list — and only leave the app from a list.
/// pipeline or chat to its list. Android list roots require two presses;
/// all other platforms retain their normal Back behavior.
@override
Future<bool> popRoute() async {
final navigator = _navigatorKey.currentState;
@@ -244,9 +252,21 @@ class AppRouterDelegate extends RouterDelegate<AppRoute> with ChangeNotifier {
return true;
}
if (_stepUp()) return true;
if (_isExitRoot) return _rootExit.handleBack();
return false;
}
bool get _isExitRoot =>
_rootExit.enabled &&
!_canStepUp &&
switch (_route.kind) {
AppRouteKind.pipelines ||
AppRouteKind.runs ||
AppRouteKind.chat ||
AppRouteKind.settings => true,
_ => false,
};
/// Whether the open route has a level above it in its own tab (a stage,
/// a run, a pipeline, a chat).
bool get _canStepUp =>
@@ -285,9 +305,16 @@ class AppRouterDelegate extends RouterDelegate<AppRoute> with ChangeNotifier {
/// history entry (or a replacement when it already matches the location).
void goTo(AppRoute route) {
if (route == _route) return;
_rootExit.clear();
_route = route;
notifyListeners();
}
@override
void dispose() {
_rootExit.dispose();
super.dispose();
}
}
/// The location a launch starts at: the browser location on the web, the
+26
View File
@@ -0,0 +1,26 @@
# Android root double-back exit
The latest request replaces the prior single-back exit rule at Home/tab roots.
Only native Android Pipelines, Runs (including filtered lists), Chat and Settings
roots intercept the first Back, showing the standard transient SnackBar
“Press back again to close”. A second Back within two seconds falls through to
the platform; no custom exit call or confirmation dialog is introduced.
The shell PopScope advertises whether root Back is currently handled, preserving
the platform's predictive back-to-home path for the second press. Detail/stage,
Search, Templates, Schedules and dialog pops keep their existing navigation.
Route changes and newly pushed dialog/detail routes clear the armed window.
Web and iOS do not enable this guard. No connection or Settings source changed.
## Evidence
- Before implementation: updated narrow/wide regression expectations failed in
seven cases because the first root Back called `SystemNavigator.pop`.
- Focused navigation suite: 26 passing tests (`app_router_test.dart`,
`pipelines_app_test.dart`, `detail_navigation_test.dart`). Includes expiry,
navigation/dialog reset, iOS bypass, browser-route updates, detail one-pop,
predictive cancellation/commit, and native exit channel assertions.
- `flutter test test/application`: 100 passing tests.
- `flutter analyze`: no issues.
- No APK build, server/deployment changes, ADB or device use. Actual mobile
behavior and rendered browser/mobile captures remain unverified.
+94 -5
View File
@@ -1,4 +1,5 @@
import 'package:flutter/widgets.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/application/app_route.dart';
import 'package:pipelines_app/application/app_router.dart';
@@ -41,19 +42,107 @@ void main() {
expect(runs, 1);
// A pipeline stage returns to its pipeline, then to the list, and the
// list leaves Back to the platform.
// list arms exit, then leaves Back to the platform.
router.goTo(AppRoute.pipelineStage(4, 'plan', version: 2));
expect(await router.popRoute(), isTrue);
expect(router.route, AppRoute.pipeline(4, version: 2));
expect(await router.popRoute(), isTrue);
expect(router.route, AppRoute.pipelines);
expect(await router.popRoute(), isTrue);
expect(await router.popRoute(), isFalse);
});
test('system Back on a list destination stays with the platform', () async {
final router = delegate(AppRoute.chat);
addTearDown(router.dispose);
test(
'Android list Back arms exit before handing it to the platform',
() async {
final router = delegate(AppRoute.chat);
addTearDown(router.dispose);
expect(await router.popRoute(), isTrue);
expect(await router.popRoute(), isFalse);
},
);
for (final root in [
AppRoute.pipelines,
AppRoute.runs,
AppRoute.runsForPipeline(3),
AppRoute.chat,
AppRoute.settings,
]) {
testWidgets('${root.path} root exit expires and navigation clears it', (
tester,
) async {
final router = AppRouterDelegate(
builder: (_, route) => Scaffold(body: Text(route.path)),
onPopToRuns: () {},
onPopToChat: () {},
cupertino: false,
initial: root,
);
addTearDown(router.dispose);
await tester.pumpWidget(
MaterialApp.router(
routerDelegate: router,
routeInformationParser: const AppRouteParser(),
routeInformationProvider: PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(
uri: Uri.parse(root.path),
),
),
),
);
await tester.pumpAndSettle();
expect(await router.popRoute(), isTrue);
await tester.pumpAndSettle();
expect(find.text('Press back again to close'), findsOneWidget);
expect(await router.popRoute(), isFalse);
await tester.pump(const Duration(seconds: 2));
await tester.pumpAndSettle();
expect(await router.popRoute(), isTrue);
await tester.pump();
router.goTo(AppRoute.pipeline(7));
await tester.pumpAndSettle();
expect(await router.popRoute(), isTrue);
await tester.pumpAndSettle();
expect(router.route, AppRoute.pipelines);
expect(find.text('Press back again to close'), findsNothing);
expect(await router.popRoute(), isTrue);
await tester.pumpAndSettle();
expect(find.text('Press back again to close'), findsOneWidget);
// Imperative dialogs also clear an already armed root exit.
final navigator = tester.state<NavigatorState>(find.byType(Navigator));
showDialog<void>(
context: navigator.overlay!.context,
builder: (_) => const AlertDialog(title: Text('Root dialog')),
);
await tester.pumpAndSettle();
expect(await router.popRoute(), isTrue);
await tester.pumpAndSettle();
expect(find.text('Root dialog'), findsNothing);
expect(await router.popRoute(), isTrue);
await tester.pumpAndSettle();
expect(await router.popRoute(), isFalse);
// Switching tabs or applying a platform/browser route re-arms exit too.
router.goTo(AppRoute.settings);
await tester.pumpAndSettle();
expect(await router.popRoute(), isTrue);
await tester.pumpAndSettle();
await router.setNewRoutePath(AppRoute.chat);
await tester.pumpAndSettle();
expect(await router.popRoute(), isTrue);
await tester.pump(const Duration(seconds: 3));
await tester.pumpWidget(const SizedBox.shrink());
});
}
test('iOS root Back is not intercepted', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
addTearDown(() => debugDefaultTargetPlatformOverride = null);
final router = delegate(AppRoute.pipelines);
addTearDown(router.dispose);
expect(await router.popRoute(), isFalse);
expect(await router.popRoute(), isFalse);
});
@@ -34,7 +34,7 @@ void main() {
for (final predictive in [false, true]) {
for (final destination in ['pipelines', 'runs', 'chat']) {
testWidgets(
'$destination: ${predictive ? 'gesture' : 'button'} Back pops dialog, detail, then app',
'$destination: ${predictive ? 'gesture' : 'button'} Back pops dialog, detail, then double-back exits',
(tester) async {
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1;
@@ -136,7 +136,20 @@ void main() {
expect(navigator.canPop(), isFalse);
expect(exits, isEmpty);
// No confirmation, double-back requirement, or hidden detail route.
// A detail pop never arms root exit. The first root Back only hints.
if (predictive) {
await backGesture(tester, 'startBackGesture');
await backGesture(tester, 'cancelBackGesture');
await tester.pumpAndSettle();
expect(find.text('Press back again to close'), findsNothing);
await backGesture(tester, 'startBackGesture');
await backGesture(tester, 'commitBackGesture');
} else {
await tester.binding.handlePopRoute();
}
await tester.pumpAndSettle();
expect(exits, isEmpty);
expect(find.text('Press back again to close'), findsOneWidget);
await tester.binding.handlePopRoute();
await tester.pumpAndSettle();
expect(exits, ['SystemNavigator.pop']);
+5 -1
View File
@@ -213,7 +213,11 @@ void main() {
expect(provider.value.uri.path, '/runs');
expect(exits, isEmpty);
// From the list, Back is left to Android. No custom exit dialog.
// From the list, the first Back hints; the second is left to Android.
await tester.binding.handlePopRoute();
await tester.pumpAndSettle();
expect(exits, isEmpty);
expect(find.text('Press back again to close'), findsOneWidget);
await tester.binding.handlePopRoute();
await tester.pumpAndSettle();
expect(find.text('Close Pipelines?'), findsNothing);