如何用GoRouter实现Cupertino风格底部弹窗的背景缩放效果?
解决方案:GoRouter + modal_bottom_sheet 实现 Cupertino 背景缩放(Dropback)效果
要在GoRouter环境下实现目标Demo中的Cupertino背景缩放效果,核心是让GoRouter的Page适配MaterialWithModalsPageRoute的逻辑——这个类正是Demo中实现背景缩放的关键。以下是具体实现步骤:
1. 自定义适配GoRouter的Modal Page类
创建一个继承自Page的自定义类,在createRoute方法中返回MaterialWithModalsPageRoute,同时集成CupertinoModalBottomSheetRoute的配置:
class CupertinoModalSheetPage extends Page { final Widget child; final bool expand; CupertinoModalSheetPage({ required this.child, this.expand = false, super.key, super.name, super.arguments, super.restorationId, }); @override Route createRoute(BuildContext context) { return MaterialWithModalsPageRoute( builder: (context) => child, fullscreenDialog: expand, settings: this, pageBuilder: (context, animation, secondaryAnimation) { return CupertinoModalBottomSheetRoute( expand: expand, backgroundColor: Colors.transparent, context: context, builder: (context) => child, // 启用背景缩放的核心配置 backdropAnimationCurve: Curves.easeInOut, backdropOpacity: 0.3, transitionAnimationController: animation, ).buildPage(context, animation, secondaryAnimation); }, ); } }
2. 在GoRouter中配置该Page
在GoRouter的路由列表里,用自定义的CupertinoModalSheetPage作为目标页面的pageBuilder返回值:
final GoRouter router = GoRouter( routes: <RouteBase>[ GoRoute( path: '/', builder: (context, state) => const HomeScreen(), routes: <RouteBase>[ GoRoute( path: 'cupertino-modal', pageBuilder: (context, state) { return CupertinoModalSheetPage( expand: true, // 对应Demo中的全屏弹窗配置 child: const CupertinoFullScreenModal(), // 你的弹窗内容组件 ); }, ), ], ), ], );
3. 关键注意点
MaterialWithModalsPageRoute会自动处理父页面的背景缩放动画,这是实现"dropback"效果的核心,必须通过自定义Page集成它,不能直接返回CupertinoModalBottomSheetRoute。- 若不需要全屏弹窗,将
expand设为false即可适配普通底部弹窗的背景缩放。 - 确保
modal_bottom_sheet包为最新版本,避免版本兼容问题导致动画失效。
内容的提问来源于stack exchange,提问作者astubenbord
相关产品推荐
相关产品推荐

