import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; /// What a back gesture needs from the page it closes. abstract interface class ContainerTransformGestureRoute implements PredictiveBackRoute { /// Whether a back gesture may start now: the page is current, at rest and /// would really pop. bool get backGestureEnabled; /// A finger took the page from the start edge. void startSwipeBack(); /// The finger moved by [fraction] of the page's width toward the end edge. void updateSwipeBack(double fraction); /// The finger let go at [velocity] page widths per second. void endSwipeBack(double velocity); } /// The back gestures of a page that shrinks into its item: the system's /// predictive back drives the page's own animation, so the shrink follows /// the finger, and releasing commits or cancels it. class ContainerTransformBackGestures extends StatelessWidget { const ContainerTransformBackGestures({ super.key, required this.route, required this.child, }); final ContainerTransformGestureRoute route; final Widget child; @override Widget build(BuildContext context) => _PredictiveBack(route: route, child: child); } /// Forwards Android's predictive back to the page, as the stock Material /// page transition does, without that transition's own shrink. class _PredictiveBack extends StatefulWidget { const _PredictiveBack({required this.route, required this.child}); final ContainerTransformGestureRoute route; final Widget child; @override State<_PredictiveBack> createState() => _PredictiveBackState(); } class _PredictiveBackState extends State<_PredictiveBack> with WidgetsBindingObserver { @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); super.dispose(); } @override bool handleStartBackGesture(PredictiveBackEvent backEvent) { if (backEvent.isButtonEvent || !widget.route.backGestureEnabled) { return false; } widget.route.handleStartBackGesture(progress: 1 - backEvent.progress); return true; } @override void handleUpdateBackGestureProgress(PredictiveBackEvent backEvent) => widget .route .handleUpdateBackGestureProgress(progress: 1 - backEvent.progress); @override void handleCancelBackGesture() => widget.route.handleCancelBackGesture(); @override void handleCommitBackGesture() => widget.route.handleCommitBackGesture(); @override Widget build(BuildContext context) => widget.child; }