Skip to content

Instantly share code, notes, and snippets.

@mercen-lee
Last active June 18, 2026 02:44
Show Gist options
  • Select an option

  • Save mercen-lee/675e5436790913e549c4cc78fac61017 to your computer and use it in GitHub Desktop.

Select an option

Save mercen-lee/675e5436790913e549c4cc78fac61017 to your computer and use it in GitHub Desktop.
iOS 26 style navigation animation implementation for Flutter
/*
How to use FullscreenSwipePage
1) Initialize in main() (required for iOS corner-radius support)
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await FullscreenSwipePage.init();
runApp(...);
}
If your native MethodChannel uses a custom name, pass it explicitly:
await FullscreenSwipePage.init(
deviceInfoChannelName: 'com.example/device_info',
);
2) Use with Navigator 2.0
Navigator(
pages: [
const FullscreenSwipePage(child: HomeView()),
if (showDetails) const FullscreenSwipePage(child: DetailsView()),
],
onPopPage: (route, result) => route.didPop(result),
)
3) Use with Navigator.push
final route = const FullscreenSwipePage(
child: DetailsView(),
).createRoute(context);
Navigator.of(context).push(route);
4) Optional gesture-conflict controls
Use popGestureConfig when a page contains horizontal gestures such as PageView,
TabBarView, sliders, waveform editors, trimmers, or drag handles.
final headerKey = GlobalKey();
final trimmerKey = GlobalKey();
FullscreenSwipePage(
popGestureConfig: FullscreenSwipePopGesturePresets.rootHorizontalPager(
alwaysEnabledRegionKeys: [headerKey],
disabledRegionKeys: [trimmerKey],
),
child: MyView(headerKey: headerKey, trimmerKey: trimmerKey),
)
5) Optional vertical-transition interop without project dependencies
If the next route uses a vertical transition, pass a route predicate instead of
importing that route/page class into this file.
FullscreenSwipePage(
isVerticalTransitionRoute: (route) => route.settings.name == '/player',
child: HomeView(),
)
6) iOS AppDelegate integration (optional: corner rounding)
FullscreenSwipePage.init() can request the display corner radius on iOS through
a MethodChannel.
- Default channel name: com.example/device_info
- Method name: getDisplayCornerRadius -> returns a double
Example Swift handler:
let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
let channel = FlutterMethodChannel(
name: "com.example/device_info",
binaryMessenger: controller.binaryMessenger
)
channel.setMethodCallHandler({ call, result in
if call.method == "getDisplayCornerRadius" {
let radius = UIScreen.main.value(forKey: "_displayCornerRadius") as? CGFloat ?? 0
result(radius)
} else {
result(FlutterMethodNotImplemented)
}
})
Notes:
- The Swift code above reads "_displayCornerRadius" via KVC, which may be
sensitive for iOS policy/review.
- On the Dart side, the channel call is attempted only when iosMajorVersion >= 26.
*/
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
bool get _isIOS => !kIsWeb && defaultTargetPlatform == TargetPlatform.iOS;
typedef FullscreenSwipeRoutePredicate = bool Function(Route<dynamic> route);
/// Configuration for the iOS fullscreen back-swipe pop gesture.
@immutable
class FullscreenSwipePopGestureConfig {
/// Whether the pop gesture is enabled for this page.
///
/// Disable this for editing screens or screens where horizontal dragging is
/// the main interaction and accidental back navigation would be harmful.
final bool enabled;
/// If true, the pop gesture is blocked when the outermost horizontal
/// PageView/TabBarView is not at page 0.
///
/// This reduces gesture conflict on horizontally paged screens.
final bool restrictToRootHorizontalPagerStart;
/// Regions where pop gesture remains enabled even when
/// [restrictToRootHorizontalPagerStart] would otherwise block it.
///
/// Useful for AppBars or headers where the back gesture should always work.
final List<GlobalKey> alwaysEnabledRegionKeys;
/// Regions where pop gesture is disabled.
///
/// Useful for waveform trimmers, sliders, scrubbers, or any widget where
/// horizontal dragging should not be stolen by the route pop gesture.
final List<GlobalKey> disabledRegionKeys;
/// Minimum movement required before accepting the pop drag.
///
/// When null, Flutter's default touch slop is used.
final double? eagerDragDistance;
const FullscreenSwipePopGestureConfig({
this.enabled = true,
this.restrictToRootHorizontalPagerStart = false,
this.alwaysEnabledRegionKeys = const [],
this.disabledRegionKeys = const [],
this.eagerDragDistance,
});
}
/// Common presets for [FullscreenSwipePopGestureConfig].
class FullscreenSwipePopGesturePresets {
FullscreenSwipePopGesturePresets._();
/// Blocks pop while the outermost horizontal pager is not at page 0.
static FullscreenSwipePopGestureConfig rootHorizontalPager({
List<GlobalKey> alwaysEnabledRegionKeys = const [],
List<GlobalKey> disabledRegionKeys = const [],
double eagerDragDistance = 10.0,
}) {
return FullscreenSwipePopGestureConfig(
restrictToRootHorizontalPagerStart: true,
alwaysEnabledRegionKeys: alwaysEnabledRegionKeys,
disabledRegionKeys: disabledRegionKeys,
eagerDragDistance: eagerDragDistance,
);
}
/// Disables pop gesture only inside [disabledRegionKey].
static FullscreenSwipePopGestureConfig disableInRegion(
GlobalKey disabledRegionKey,
) {
return FullscreenSwipePopGestureConfig(
disabledRegionKeys: [disabledRegionKey],
);
}
}
/// A [Page] that provides an iOS-style fullscreen back-swipe pop gesture.
class FullscreenSwipePage<T> extends Page<T> {
static double displayCornerRadius = 0;
static int iosMajorVersion = 0;
/// Initializes iOS-only values used by the transition.
static Future<void> init({
String deviceInfoChannelName = 'com.example/device_info',
}) async {
if (!_isIOS) return;
try {
final channel = MethodChannel(deviceInfoChannelName);
final version = Platform.operatingSystemVersion;
final versionMatch = RegExp(r'(\d+)').firstMatch(version);
if (versionMatch != null) {
iosMajorVersion = int.tryParse(versionMatch.group(1)!) ?? 0;
}
if (iosMajorVersion >= 26) {
final radius = await channel.invokeMethod<double>(
'getDisplayCornerRadius',
);
if (radius != null) {
displayCornerRadius = radius;
}
}
} catch (_) {}
}
final Widget child;
/// Gesture behavior for this page.
final FullscreenSwipePopGestureConfig popGestureConfig;
/// Optional predicate for routes that should be treated as vertical routes.
///
/// This replaces project-specific checks such as `route.settings is MyPage`.
/// Return true for routes where this page should not apply horizontal
/// secondary parallax/dimming while that next route is active.
final FullscreenSwipeRoutePredicate? isVerticalTransitionRoute;
/// Background used behind overscroll and rounded corners.
///
/// Defaults to [ThemeData.scaffoldBackgroundColor].
final Color? backgroundColor;
/// Overlay color used for dimming.
///
/// Defaults to [Colors.black].
final Color? overlayColor;
const FullscreenSwipePage({
required this.child,
this.popGestureConfig = const FullscreenSwipePopGestureConfig(),
this.isVerticalTransitionRoute,
this.backgroundColor,
this.overlayColor,
super.key,
super.name,
super.arguments,
super.restorationId,
});
@override
Route<T> createRoute(BuildContext context) {
return FullscreenSwipeRoute<T>(page: this);
}
}
class FullscreenSwipeRoute<T> extends PageRoute<T> {
bool _isScrolling = false;
bool _isNextVertical = false;
bool _isRootHorizontalPagerAtStart = true;
int? _rootHorizontalPagerDepth;
FullscreenSwipeRoute({required FullscreenSwipePage<T> page})
: super(settings: page);
FullscreenSwipePage<T> get _page => settings as FullscreenSwipePage<T>;
FullscreenSwipePopGestureConfig get _popGestureConfig =>
_page.popGestureConfig;
bool _canStartPopGesture() {
if (!_isIOS) return false;
if (!_popGestureConfig.enabled) return false;
if (_isScrolling) return false;
if (isFirst) return false;
if (!(navigator?.canPop() ?? false)) return false;
if (willHandlePopInternally) return false;
if (popDisposition == RoutePopDisposition.doNotPop) return false;
final routeAnimation = animation;
final routeSecondaryAnimation = secondaryAnimation;
if (routeAnimation == null || routeSecondaryAnimation == null) return false;
if (routeAnimation.status != AnimationStatus.completed) return false;
if (routeSecondaryAnimation.status != AnimationStatus.dismissed) {
return false;
}
return true;
}
bool _canStartPopGestureAt(PointerEvent event) {
final config = _popGestureConfig;
if (_isPointerInAnyRegion(config.disabledRegionKeys, event)) {
return false;
}
if (!config.restrictToRootHorizontalPagerStart) {
return true;
}
if (_isRootHorizontalPagerAtStart) {
return true;
}
if (_isPointerInAnyRegion(config.alwaysEnabledRegionKeys, event)) {
return true;
}
return false;
}
_SwipePopGestureController<T> _startPopGesture() {
return _SwipePopGestureController<T>(
navigator: navigator!,
controller: controller!,
getIsActive: () => isActive,
getIsCurrent: () => isCurrent,
);
}
@override
Duration get transitionDuration => const Duration(milliseconds: 350);
@override
Duration get reverseTransitionDuration => const Duration(milliseconds: 350);
@override
bool get opaque => true;
@override
bool get barrierDismissible => false;
@override
Color? get barrierColor => null;
@override
String? get barrierLabel => null;
@override
bool get maintainState => true;
@override
bool canTransitionTo(TransitionRoute<dynamic> nextRoute) {
final isAllowedVertical =
_page.isVerticalTransitionRoute?.call(nextRoute) ?? false;
return nextRoute is FullscreenSwipeRoute || isAllowedVertical;
}
@override
bool canTransitionFrom(TransitionRoute<dynamic> previousRoute) {
return previousRoute is PageRoute;
}
@override
void didChangeNext(Route<dynamic>? nextRoute) {
super.didChangeNext(nextRoute);
_isNextVertical =
nextRoute != null &&
(_page.isVerticalTransitionRoute?.call(nextRoute) ?? false);
}
@override
Widget buildPage(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) {
return NotificationListener<ScrollNotification>(
onNotification: (notification) {
if (notification is ScrollStartNotification) {
_isScrolling = true;
} else if (notification is ScrollEndNotification) {
_isScrolling = false;
}
_updateRootHorizontalPagerState(notification);
return false;
},
child: _page.child,
);
}
void _updateRootHorizontalPagerState(ScrollNotification notification) {
if (!_popGestureConfig.restrictToRootHorizontalPagerStart) {
return;
}
if (notification.metrics.axis != Axis.horizontal) {
return;
}
if (notification.metrics is! PageMetrics) {
return;
}
final depth = notification.depth;
final rootDepth = _rootHorizontalPagerDepth;
if (rootDepth == null || depth < rootDepth) {
_rootHorizontalPagerDepth = depth;
}
if (depth != _rootHorizontalPagerDepth) {
return;
}
final metrics = notification.metrics as PageMetrics;
final page = metrics.page;
final fallbackPage = metrics.viewportDimension == 0
? 0.0
: metrics.pixels / metrics.viewportDimension;
_isRootHorizontalPagerAtStart = (page ?? fallbackPage) <= 0.0001;
}
@override
Widget buildTransitions(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
final bool isUserGesture = navigator?.userGestureInProgress ?? false;
final Animation<double> effectiveAnimation = isUserGesture
? animation
: CurvedAnimation(
parent: animation,
curve: const Cubic(0.2, 0.0, 0.0, 1.0),
reverseCurve: const Cubic(0.2, 0.0, 0.0, 1.0).flipped,
);
final Animation<double> effectiveSecondaryAnimation = isUserGesture
? secondaryAnimation
: CurvedAnimation(
parent: secondaryAnimation,
curve: const Cubic(0.2, 0.0, 0.0, 1.0),
reverseCurve: const Cubic(0.2, 0.0, 0.0, 1.0).flipped,
);
final slideAnimation = effectiveAnimation.drive(
Tween<Offset>(begin: const Offset(1, 0), end: Offset.zero),
);
final previousScreenSlide = effectiveSecondaryAnimation.drive(
Tween<Offset>(begin: Offset.zero, end: const Offset(-0.3, 0)),
);
final overlayOpacity = effectiveSecondaryAnimation.drive(
Tween<double>(begin: 0.0, end: _isNextVertical ? 0.12 : 0.1),
);
final backgroundColor =
_page.backgroundColor ?? Theme.of(context).scaffoldBackgroundColor;
final overlayColor = _page.overlayColor ?? Colors.black;
final pageContent = _SwipePopGestureDetector(
enabledCallback: _canStartPopGesture,
startCallback: _canStartPopGestureAt,
onStartPopGesture: _startPopGesture,
backgroundColor: backgroundColor,
overlayColor: overlayColor,
eagerDragDistance: _popGestureConfig.eagerDragDistance,
child: AnimatedBuilder(
animation: animation,
builder: (context, _) {
final isGestureActive = animation.value < 1.0;
final shouldRoundCorners =
isGestureActive &&
FullscreenSwipePage.displayCornerRadius > 0 &&
secondaryAnimation.isDismissed;
return SlideTransition(
position: slideAnimation,
child: shouldRoundCorners
? ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(
FullscreenSwipePage.displayCornerRadius,
),
bottomLeft: Radius.circular(
FullscreenSwipePage.displayCornerRadius,
),
),
child: ColoredBox(
color: backgroundColor,
child: child,
),
)
: child,
);
},
),
);
final overlay = Positioned.fill(
child: IgnorePointer(
child: FadeTransition(
opacity: overlayOpacity,
child: ColoredBox(color: overlayColor),
),
),
);
if (_isNextVertical) {
return pageContent;
}
return SlideTransition(
position: previousScreenSlide,
child: Stack(
children: [pageContent, if (!secondaryAnimation.isDismissed) overlay],
),
);
}
static bool _isPointerInAnyRegion(List<GlobalKey> keys, PointerEvent event) {
for (final key in keys) {
if (_isPointerInRegion(key, event)) {
return true;
}
}
return false;
}
static bool _isPointerInRegion(GlobalKey? key, PointerEvent event) {
if (key == null) {
return false;
}
final targetContext = key.currentContext;
if (targetContext == null) {
return false;
}
final renderObject = targetContext.findRenderObject();
if (renderObject is! RenderBox || !renderObject.hasSize) {
return false;
}
final offset = renderObject.localToGlobal(Offset.zero);
final rect = offset & renderObject.size;
return rect.contains(event.position);
}
}
class _SwipePopGestureDetector extends StatefulWidget {
const _SwipePopGestureDetector({
required this.child,
required this.enabledCallback,
required this.startCallback,
required this.onStartPopGesture,
required this.backgroundColor,
required this.overlayColor,
required this.eagerDragDistance,
});
final Widget child;
final bool Function() enabledCallback;
final bool Function(PointerEvent event) startCallback;
final _SwipePopGestureController Function() onStartPopGesture;
final Color backgroundColor;
final Color overlayColor;
final double? eagerDragDistance;
@override
State<_SwipePopGestureDetector> createState() =>
_SwipePopGestureDetectorState();
}
class _SwipePopGestureDetectorState extends State<_SwipePopGestureDetector>
with SingleTickerProviderStateMixin {
_SwipePopGestureController? _controller;
double _overscroll = 0.0;
late AnimationController _overscrollController;
late Animation<double> _overscrollAnimation;
@override
void initState() {
super.initState();
_overscrollController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 350),
);
_overscrollAnimation = _overscrollController.drive(
Tween<double>(begin: 0, end: 0),
);
}
@override
void dispose() {
_overscrollController.dispose();
super.dispose();
}
void _handleDragStart(DragStartDetails details) {
if (widget.enabledCallback()) {
_controller = widget.onStartPopGesture();
_controller!.onOverscroll = (value) {
setState(() {
_overscroll = value;
});
};
}
}
void _handleDragUpdate(DragUpdateDetails details) {
final controller = _controller;
final delta = details.primaryDelta ?? details.delta.dx;
final size = context.size;
if (controller == null || size == null) return;
controller.dragUpdate(delta, size.width);
}
void _handleDragEnd(DragEndDetails details) {
final controller = _controller;
final size = context.size;
if (controller != null && size != null) {
final velocity = details.velocity.pixelsPerSecond.dx / size.width;
final willPop = controller.willPop(velocity);
controller.dragEnd(velocity);
if (_overscroll != 0) {
if (willPop) {
setState(() {
_overscroll = 0;
});
} else {
_overscrollController.duration = const Duration(milliseconds: 350);
_overscrollAnimation = Tween<double>(begin: _overscroll, end: 0)
.animate(
CurvedAnimation(
parent: _overscrollController,
curve: Curves.easeOutQuint,
),
);
_overscrollController.reset();
_overscrollController.forward().then((_) {
setState(() {
_overscroll = 0;
});
});
}
}
}
_controller = null;
}
void _handleDragCancel() {
_controller?.dragEnd(0);
_controller = null;
setState(() {
_overscroll = 0;
});
}
@override
Widget build(BuildContext context) {
return RawGestureDetector(
gestures: <Type, GestureRecognizerFactory>{
_AlwaysWinHorizontalDragGestureRecognizer:
GestureRecognizerFactoryWithHandlers<
_AlwaysWinHorizontalDragGestureRecognizer
>(
() => _AlwaysWinHorizontalDragGestureRecognizer(
debugOwner: this,
enabledCallback: widget.enabledCallback,
startCallback: widget.startCallback,
eagerDragDistance: widget.eagerDragDistance,
),
(_AlwaysWinHorizontalDragGestureRecognizer instance) {
instance
..onStart = _handleDragStart
..onUpdate = _handleDragUpdate
..onEnd = _handleDragEnd
..onCancel = _handleDragCancel
..dragStartBehavior = DragStartBehavior.start;
},
),
},
behavior: HitTestBehavior.translucent,
child: AnimatedBuilder(
animation: _overscrollController,
builder: (context, child) {
final offset = _overscrollController.isAnimating
? _overscrollAnimation.value
: _overscroll;
final isOverflowing = offset > 0 || offset < 0;
final cornerRadius = FullscreenSwipePage.displayCornerRadius;
return Stack(
clipBehavior: Clip.none,
children: [
if (isOverflowing) ...[
Positioned.fill(
child: ColoredBox(color: widget.backgroundColor),
),
Positioned.fill(
child: ColoredBox(
color: widget.overlayColor.withValues(alpha: 0.1),
),
),
],
Transform.translate(
offset: Offset(offset, 0),
child: isOverflowing && cornerRadius > 0
? ClipRRect(
borderRadius: BorderRadius.only(
topRight: Radius.circular(cornerRadius),
bottomRight: Radius.circular(cornerRadius),
),
child: widget.child,
)
: widget.child,
),
],
);
},
),
);
}
}
/// Controls the route pop gesture so it does not blindly steal every horizontal
/// gesture on the page.
class _AlwaysWinHorizontalDragGestureRecognizer
extends HorizontalDragGestureRecognizer {
_AlwaysWinHorizontalDragGestureRecognizer({
super.debugOwner,
required this.enabledCallback,
required this.startCallback,
required this.eagerDragDistance,
});
final bool Function() enabledCallback;
final bool Function(PointerEvent event) startCallback;
final double? eagerDragDistance;
@override
bool isPointerAllowed(PointerEvent event) {
if (!enabledCallback()) {
return false;
}
if (!startCallback(event)) {
return false;
}
return super.isPointerAllowed(event);
}
@override
bool hasSufficientGlobalDistanceToAccept(
PointerDeviceKind pointerDeviceKind,
double? deviceTouchSlop,
) {
if (!enabledCallback()) {
return false;
}
if (globalDistanceMoved <= 0) {
return false;
}
final distance = eagerDragDistance;
if (distance != null) {
return globalDistanceMoved > distance;
}
return super.hasSufficientGlobalDistanceToAccept(
pointerDeviceKind,
deviceTouchSlop,
);
}
}
class _SwipePopGestureController<T> {
_SwipePopGestureController({
required this.navigator,
required this.controller,
required this.getIsActive,
required this.getIsCurrent,
}) {
navigator.didStartUserGesture();
}
final NavigatorState navigator;
final AnimationController controller;
final ValueGetter<bool> getIsActive;
final ValueGetter<bool> getIsCurrent;
ValueChanged<double>? onOverscroll;
double _overscroll = 0.0;
bool _gestureStarted = false;
void dragUpdate(double deltaPixels, double width) {
final bool enableOverflow =
!_isIOS || FullscreenSwipePage.iosMajorVersion >= 26;
if (!_gestureStarted && deltaPixels > 0) {
_gestureStarted = true;
}
if (_overscroll != 0.0 && enableOverflow) {
final resistance = 1.0 / (1.0 + (_overscroll.abs() / width) * 20);
final prevOverscroll = _overscroll;
_overscroll += deltaPixels * resistance;
if ((prevOverscroll > 0 && _overscroll <= 0) ||
(prevOverscroll < 0 && _overscroll >= 0)) {
final excessOverscroll = _overscroll;
_overscroll = 0;
final deltaProgress = excessOverscroll / width;
final newProgress = controller.value - deltaProgress;
controller.value = newProgress.clamp(0.0, 1.0);
}
} else {
final deltaProgress = deltaPixels / width;
final newProgress = controller.value - deltaProgress;
if (enableOverflow && newProgress < 0.0 && _gestureStarted) {
controller.value = 0.0;
_overscroll = (-newProgress) * width;
} else if (enableOverflow && newProgress > 1.0 && _gestureStarted) {
controller.value = 1.0;
_overscroll = -((newProgress - 1.0) * width);
} else {
controller.value = newProgress.clamp(0.0, 1.0);
}
}
onOverscroll?.call(_overscroll);
}
bool willPop(double velocity) {
if (velocity.abs() >= 1.0) {
return velocity > 0;
} else {
return controller.value < 0.5;
}
}
void dragEnd(double velocity) {
const Curve animationCurve = Curves.easeOutQuint;
final bool isCurrent = getIsCurrent();
final bool animateForward;
if (!isCurrent) {
animateForward = getIsActive();
} else if (velocity.abs() >= 1.0) {
animateForward = velocity < 0;
} else {
animateForward = controller.value > 0.5;
}
if (animateForward) {
controller.animateTo(
1.0,
duration: const Duration(milliseconds: 350),
curve: animationCurve,
);
} else {
if (isCurrent) {
navigator.pop();
}
if (controller.isAnimating) {
controller.animateBack(
0.0,
duration: const Duration(milliseconds: 350),
curve: animationCurve,
);
}
}
if (controller.isAnimating) {
late AnimationStatusListener animationStatusCallback;
animationStatusCallback = (AnimationStatus status) {
navigator.didStopUserGesture();
controller.removeStatusListener(animationStatusCallback);
};
controller.addStatusListener(animationStatusCallback);
} else {
navigator.didStopUserGesture();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment