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? _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 route, Route? 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(); } }