如何在Flutter中使用Lottie包显示JSON动画?我用Image.asset无法加载
在Flutter中使用Lottie包加载JSON动画的方法
Image.asset()仅支持加载PNG、JPG等图片格式资源,Lottie动画JSON属于矢量动画文件,必须用专门的Lottie包解析渲染。以下是具体实现步骤:
1. 添加Lottie依赖
在项目根目录的pubspec.yaml文件中,添加Lottie包的依赖:
dependencies: flutter: sdk: flutter lottie: ^2.7.0 # 可替换为最新版本
保存后执行flutter pub get拉取依赖。
2. 配置动画资源
- 将Lottie格式的JSON动画文件放到项目的
assets目录下(可创建assets/animations文件夹统一存放),例如路径为assets/animations/success.json。 - 在
pubspec.yaml的flutter区块中声明资源路径:
flutter: assets: - assets/animations/success.json
3. 加载并显示动画
导入Lottie包后,使用Lottie.asset()组件加载本地JSON动画:
import 'package:flutter/material.dart'; import 'package:lottie/lottie.dart'; class LottieDemo extends StatelessWidget { const LottieDemo({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Lottie.asset( 'assets/animations/success.json', width: 300, height: 300, fit: BoxFit.contain, // 可选参数:控制动画行为 repeat: true, // 是否循环播放 reverse: false, // 是否倒放 animate: true, // 是否自动播放 ), ), ); } }
进阶:手动控制动画播放
如果需要自定义播放逻辑(比如点击触发播放、暂停),可以结合AnimationController实现:
import 'package:flutter/material.dart'; import 'package:lottie/lottie.dart'; class LottieControllerDemo extends StatefulWidget { const LottieControllerDemo({super.key}); @override State<LottieControllerDemo> createState() => _LottieControllerDemoState(); } class _LottieControllerDemoState extends State<LottieControllerDemo> with SingleTickerProviderStateMixin { late AnimationController _animationController; @override void initState() { super.initState(); // 创建动画控制器 _animationController = AnimationController( vsync: this, duration: const Duration(seconds: 3), ); } @override void dispose() { // 销毁控制器,避免内存泄漏 _animationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Lottie.asset( 'assets/animations/success.json', controller: _animationController, onLoaded: (composition) { // 动画加载完成后,同步控制器时长 _animationController.duration = composition.duration; }, width: 300, height: 300, ), const SizedBox(height: 20), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( onPressed: () => _animationController.play(), child: const Text('播放'), ), const SizedBox(width: 10), ElevatedButton( onPressed: () => _animationController.pause(), child: const Text('暂停'), ), const SizedBox(width: 10), ElevatedButton( onPressed: () => _animationController.reset(), child: const Text('重置'), ), ], ) ], ), ), ); } }
注意事项
- 确保你的JSON文件是标准Lottie格式,普通JSON无法被渲染。
- 检查
pubspec.yaml中的资源路径是否与实际文件路径一致,路径错误会导致加载失败。
内容的提问来源于stack exchange,提问作者Vrusti Patel
相关产品推荐
相关产品推荐

