Flutter — 使用 Lottie 製作 Splash Page

上一篇我們在 前端動畫解決方案 — Lottie 介紹了在網頁使用 Lottie 製作動畫效果,這次要分享在 Flutter 使用 Lottie 製作一個 Splash Page

安裝及配置

首先我們要先安裝 Lottie

打開 pubspec.yaml 在 dependencies 增加 lottie

dependencies:
lottie: ^0.4.0+1

執行 flutter pub get 安裝套件

前一篇我們有提到會使用 AE 導出的 JSON 檔案,在 flutter 中需要設定 JSON 檔案的位置,一樣在 pubspec.yaml 增加資源路徑即可,並將 JSON 檔案放在指定路徑。

flutter:
assets:
- assets/lottie/

設定起始頁及路由

在 main.dark 引入 home.dart 以及 splash.dart

MaterialApp

  • home : App 進入後的第一個頁面,splash 做為打開 App 後先看到的載入頁面。
  • routes : 動畫播放完畢需要跳轉到真正的首頁 home,所以在路由這邊設定首頁的路徑 ‘/home’

實作

設定好路由和首頁後,接著我們開始來實作 Splash page

1. 建立 StatefulWidget

2. AnimationController

AnimationController 是 Flutter 中控制動畫的類別,包含的方法有 forwardstopreverse。需要定義一個 AnimationController 來播放 AE 動畫。

在 initState 建立 一個 AnimationController

_controller =
AnimationController(vsync: this, duration: Duration(seconds: 4))

duration: 動畫持續時間。

vsync : vsync 會綁定一個動畫計時器到 widget ,當這個 widget 不再顯示時,動畫會被暫停,一直到 widget 再顯示才會播放動畫,這樣可以避免消耗不必要的資源。

⚠️ 使用 vsync 要先繼承 SingleTickerProviderStateMixin

不要忘記在dispose銷毀 _controller,釋放資源

⚠️ 注意 AnimationController 被建立好後還不會馬上播放動畫,後面會使用 Lottie 來觸發動畫播放。

3. 建立 Lottie StatelessWidget

在 splash.dart 引入 lottie ,並新增一個 StatelessWidget

import 'package:lottie/lottie.dart';

使用 Lottie 很簡單 ,就和使用圖片差不多

Lottie.asset('your path')

但我們需要更多的設定,下面介紹幾個常用的參數

composition: 動畫檔案 (必傳)

repeat: bool 是否重複播放動畫

reverse: bool 逆向播放動畫

controller: 對應的 AnimationController

width, height: double 動畫長寬

fit: BoxFit 圖片填充方式

  • BoxFit.fill,填滿
  • BoxFit.contain,原大小
  • BoxFit.cover,延伸填滿
  • BoxFit.fitWidth,填滿寬度
  • BoxFit.fitHeight,填滿高度
  • BoxFit.none,不做變化

alignment: Alignment 對齊方式

onLoaded: Function 動畫載入後觸發的方法

frameBuilder: 可以替動畫加上一些效果,像是放大縮小、淡化等

controller 的部分我們需要引用前面的 AnimationController 來播放動畫,所以用 findAncestorStateOfType 拿到父級別的 state , state._controller 就是先前我們先創建好的 AnimationController 。

在 Lottie 觸發 onLoaded 的時候播放動畫,所以用了 forward 方法。

而 onLoaded 會回傳參數 composition 可以拿到動畫的總時間,藉此綁在 controller 上,所以上面的 controller 的 duration 就可以拿掉了,除非你需要自訂動畫的持續時間再使用即可。

*initState 的 _controller 拿掉 duration
_controller = AnimationController(vsync: this)
*onLoaded 綁定 duration
state._controller.duration = composition.duration
state._controller.forward();

補充:dart 提供鏈結式的寫法,程式碼會更簡潔一點 😆

onLoaded 可以改成這樣寫state._controller
..duration = composition.duration
..forward();
Lottie 完整程式碼

接著在 _SplashPageState Widget build 回傳 LottieAnimate() 就可以了!

4. 跳轉到真正的首頁

最後要讓動畫播放完畢後 push 到 ‘/home’,這邊也很簡單,只要在 AnimationController 監聽動畫的播放狀態再 Navigator push 即可。

以上 Splash page 的實作就完成了!來看看實際的畫面 🎉

file from https://lottiefiles.com/19902-splash-screen

附上 splash 完整的程式碼

結語

Lottie 的網頁和 Flutter上的應用介紹結束了,這種做法設計師也需要學會 AE 等工具才可行,如果是個人需求或是沒辦法使用 AE 的話不妨也可以在 lottiefiles 上面找到一些付費/免費的資源喔!🎉

--

--