來源:https://github.com/CarGuo/GSYGithubAppFlutter
1、在flutter配置文件pubspec.yaml中添加依賴,如下:
dependencies:
flutter_lottie: ^0.2.0
2、根據(jù)github上的添加以下代碼到info.plist,文件目錄:project/ios/Runner/Info.plist
<key>io.flutter.embedded_views_preview</key>
<true />
3、將json格式的動(dòng)畫拖到項(xiàng)目中,然后在pubspec.yaml中添加路徑
assets:
- static/file/rejection2.json
4、在代碼中直接引用,如下所示
@override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
child: Center(
child: Container(
width: 200,
height: 200,
color: Colors.white,
child: LottieView.fromFile(
filePath: 'static/file/rejection2.json',
autoPlay: true,
loop: true,
reverse: false,
),
),
),
);
}
5、這時(shí)候在iOS上跑代碼會(huì)發(fā)現(xiàn)提示正在pod install(停留時(shí)間很長),但是會(huì)安裝失敗,原因是flutter_lottie在iOS項(xiàng)目上依賴lottie-ios,而lottie-ios又是swift項(xiàng)目,所以需要在podfile中打開use_frameworks,podfile目錄:project/ios/podfile,
target 'Runner' do
use_frameworks!
6、重新編譯運(yùn)行,又會(huì)報(bào)錯(cuò),原因是swift版本不對,用xcode打開iOS目錄下的項(xiàng)目,按下圖選擇swift版本

swift版本選擇.png
7、回到flutter項(xiàng)目,再次運(yùn)行,OK!效果如下(截取的是安卓界面):

flutter_lottie運(yùn)行效果.gif
注意:運(yùn)行一些比較炫酷的動(dòng)畫時(shí),安卓手機(jī)會(huì)崩潰,會(huì)出現(xiàn)以下錯(cuò)誤,

安卓運(yùn)行出錯(cuò).png
是因?yàn)閒lutter-lottie中依賴的lottie-android版本為2.7.x,需要最新的3.0版本以上才可以。那么如何修改呢?
a. 選擇代碼中的LottieView跳轉(zhuǎn)到第三方庫中

option鍵+點(diǎn)擊LottiveView.png
b. 在工具欄,按下圖選擇android目錄

選擇android目錄.png
c. 在工具欄,按下圖選擇build.gradle文件

選擇build.gradle.png
d. 拉倒文件最下方,找到dependencies,修改版本號
dependencies {
implementation 'com.airbnb.android:lottie:3.0.2'
}
e. 重新運(yùn)行項(xiàng)目