如何在Flutter Hero过渡动画中控制组件宽高,自定义flightShuttleBuilder尺寸
问题原因
Hero组件在执行过渡动画时,系统会自动计算起点Hero和终点Hero的尺寸差值,对flightShuttleBuilder返回的组件施加动态的尺寸过渡约束,你自定义的Container宽高会被这层父级约束覆盖,因此不生效。
解决方案
你只需要在flightShuttleBuilder返回的组件外层套一个UnconstrainedBox,解除父级的强制尺寸约束即可,修改后的代码片段如下:
flightShuttleBuilder: ( BuildContext flightContext, Animation<double> animation, HeroFlightDirection flightDirection, BuildContext fromHeroContext, BuildContext toHeroContext, ) { return AnimatedBuilder( animation: animation, builder: (context, child) { // 外层添加UnconstrainedBox解除父级强制约束 return UnconstrainedBox( child: Container( height: 200, width: 200, decoration: BoxDecoration( color: Colors.green, ), ), ); }, ); }
如果需要保留部分父级约束,也可以用OverflowBox锁定固定尺寸:
return OverflowBox( minHeight: 200, maxHeight: 200, minWidth: 200, maxWidth: 200, child: Container( decoration: BoxDecoration( color: Colors.green, ), ), );
修改后你设置的200*200尺寸就会正常生效。
内容的提问来源于stack exchange,提问作者sumit kumar Pradhan
相关产品推荐
相关产品推荐

