Lottie设置全屏后从左上角扩展,如何保持居中显示?
解决Lottie适配全屏时中心偏移的问题
你遇到的问题源于直接设置width和height为double.infinity时,Lottie的布局约束与内部渲染逻辑冲突,导致alignment属性未正常生效。以下是两种可行的解决方案:
方案一:用SizedBox.expand包裹Lottie
SizedBox.expand会强制子组件填充整个可用空间,同时让Lottie的对齐和适配逻辑正常工作:
Widget build(BuildContext context) { return Scaffold( body: SizedBox.expand( child: Lottie.asset( 'splash_logo.json', alignment: Alignment.center, repeat: true, fit: BoxFit.cover, ), ), ); }
方案二:明确绑定屏幕尺寸
通过MediaQuery获取屏幕宽高,直接赋值给Lottie,确保它在已知尺寸范围内保持中心对齐:
Widget build(BuildContext context) { final screenSize = MediaQuery.of(context).size; return Scaffold( body: Center( child: Lottie.asset( 'splash_logo.json', alignment: Alignment.center, repeat: true, width: screenSize.width, height: screenSize.height, fit: BoxFit.cover, ), ), ); }
补充说明
- 若需保留动画原始比例并铺满屏幕,保留
BoxFit.cover即可;若允许拉伸动画以完全填充屏幕,可将fit改为BoxFit.fill。 - 避免同时使用
Center组件和double.infinity的宽高设置,这会造成布局约束冲突,反而导致对齐逻辑失效。
内容的提问来源于stack exchange,提问作者Shanu
相关产品推荐
相关产品推荐

