如何在go_router路由中使用animations库的OpenContainer容器过渡?
在GoRouter中复用OpenContainer风格的路由过渡
不用完全自定义过渡,有两种更简便的方案:
方案一:直接用OpenContainer包裹触发组件(推荐)
OpenContainer本身就是为组件级过渡跳转设计的,不需要强行适配GoRouter的transitionsBuilder,直接用它替代普通的导航触发组件即可,同时同步路由栈避免状态不一致:
OpenContainer( // 触发过渡的组件(比如按钮、卡片) closedBuilder: (context, openAction) => ElevatedButton( onPressed: openAction, child: const Text('跳转到目标页'), ), // 目标页面内容 openBuilder: (context, closeAction) => const TargetScreen(), // 过渡关闭后同步GoRouter的路由栈 onClosed: (_) => GoRouter.of(context).pop(), )
这种方式完全复用OpenContainer的原生动画逻辑,包括时序、曲线和容器展开效果,同时保证GoRouter的路由栈状态正确。
方案二:提取OpenContainer的动画逻辑到CustomTransitionPage
如果需要通过GoRouter的CustomTransitionPage实现全局页面过渡,可以复用animations库内置的过渡组件(OpenContainer底层依赖这些),模拟它的默认风格:
GoRoute( path: '/target', pageBuilder: (context, state) => CustomTransitionPage( child: const TargetScreen(), transitionsBuilder: (context, animation, secondaryAnimation, child) { // 复用animations库的FadeThroughTransition,和OpenContainer默认过渡风格一致 return FadeThroughTransition( animation: animation, secondaryAnimation: secondaryAnimation, child: child, ); }, ), )
注意:这种方式是页面级全局过渡,无法实现OpenContainer那种从特定组件展开的精准锚点效果,适合不需要组件锚定的场景。
内容的提问来源于stack exchange,提问作者yo.ian.g
相关产品推荐
相关产品推荐

