對于一個前端的App來說,添加適當(dāng)?shù)膭赢?,可以給用戶更好的體驗和視覺效果。所以無論是原生的iOS或Android,還是前端開發(fā)中都會提供完成某些動畫的API。
Flutter有自己的渲染閉環(huán),我們當(dāng)然可以給它提供一定的數(shù)據(jù)模型,來讓它幫助我們實現(xiàn)對應(yīng)的動畫效果。
一. 動畫API認(rèn)識
動畫其實是我們通過某些方式(比如對象,Animation對象)給Flutter引擎提供不同的值,而Flutter可以根據(jù)我們提供的值,給對應(yīng)的Widget添加順滑的動畫效果。
針對動畫這個章節(jié),我打算先理清楚他們的API關(guān)系和作用,再來講解如何利用這些API來實現(xiàn)不同的動畫效果。
1.1. Animation
在Flutter中,實現(xiàn)動畫的核心類是Animation,Widget可以直接將這些動畫合并到自己的build方法中來讀取它們的當(dāng)前值或者監(jiān)聽它們的狀態(tài)變化。
我們一起來看一下Animation這個類,它是一個抽象類:
- addListener方法
- 當(dāng)動畫的狀態(tài)值發(fā)生變化時,動畫都會通知所有通過
addListener添加的監(jiān)聽器。 - 通常,一個正在監(jiān)聽動畫的
state對象會調(diào)用自身的setState方法,將自身傳入這些監(jiān)聽器的回調(diào)函數(shù)來通知 widget 系統(tǒng)需要根據(jù)新狀態(tài)值進(jìn)行重新構(gòu)建。
- 當(dāng)動畫的狀態(tài)值發(fā)生變化時,動畫都會通知所有通過
- addStatusListener
- 當(dāng)動畫的狀態(tài)發(fā)生變化時,會通知所有通過
addStatusListener添加的監(jiān)聽器。 - 通常情況下,動畫會從
dismissed狀態(tài)開始,表示它處于變化區(qū)間的開始點。 - 舉例來說,從 0.0 到 1.0 的動畫在
dismissed狀態(tài)時的值應(yīng)該是 0.0。 - 動畫進(jìn)行的下一狀態(tài)可能是
forward(比如從 0.0 到 1.0)或者reverse(比如從 1.0 到 0.0)。 - 最終,如果動畫到達(dá)其區(qū)間的結(jié)束點(比如 1.0),則動畫會變成
completed狀態(tài)。
- 當(dāng)動畫的狀態(tài)發(fā)生變化時,會通知所有通過
Animation源碼如下:
abstract class Animation<T> extends Listenable implements ValueListenable<T> {
const Animation();
// 添加動畫監(jiān)聽器
@override
void addListener(VoidCallback listener);
// 移除動畫監(jiān)聽器
@override
void removeListener(VoidCallback listener);
// 添加動畫狀態(tài)監(jiān)聽器
void addStatusListener(AnimationStatusListener listener);
// 移除動畫狀態(tài)監(jiān)聽器
void removeStatusListener(AnimationStatusListener listener);
// 獲取動畫當(dāng)前狀態(tài)
AnimationStatus get status;
// 獲取動畫當(dāng)前的值
@override
T get value;
1.2. AnimationController
Animation是一個抽象類,并不能用來直接創(chuàng)建對象實現(xiàn)動畫的使用。
- AnimationController是Animation的一個子類,實現(xiàn)動畫通常我們需要創(chuàng)建AnimationController對象。
- AnimationController會生成一系列的值,默認(rèn)情況下值是0.0到1.0區(qū)間的值;
除了上面的監(jiān)聽,獲取動畫的狀態(tài)、值之外,AnimationController還提供了對動畫的控制:
- forward:向前執(zhí)行動畫
- reverse:方向播放動畫
- stop:停止動畫
AnimationController源碼如下:
class AnimationController extends Animation<double>
with AnimationEagerListenerMixin, AnimationLocalListenersMixin, AnimationLocalStatusListenersMixin {
AnimationController({
// 初始化值
double value,
// 動畫執(zhí)行的時間
this.duration,
// 反向動畫執(zhí)行的時間
this.reverseDuration,
// 最小值
this.lowerBound = 0.0,
// 最大值
this.upperBound = 1.0,
// 刷新率ticker的回調(diào)(看下面詳細(xì)解析)
@required TickerProvider vsync,
})
}
AnimationController有一個必傳的參數(shù)vsync,它是什么呢?
- 之前我講過關(guān)于Flutter的渲染閉環(huán),F(xiàn)lutter每次渲染一幀畫面之前都需要等待一個vsync信號。
- 這里也是為了監(jiān)聽vsync信號,當(dāng)Flutter開發(fā)的應(yīng)用程序不再接受同步信號時(比如鎖屏或退到后臺),那么繼續(xù)執(zhí)行動畫會消耗性能。
- 這個時候我們設(shè)置了Ticker,就不會再出發(fā)動畫了。
- 開發(fā)中比較常見的是將SingleTickerProviderStateMixin混入到State的定義中。
1.3. CurvedAnimation
CurvedAnimation也是Animation的一個實現(xiàn)類,它的目的是為了給AnimationController增加動畫曲線。
- CurvedAnimation可以將AnimationController和Curve結(jié)合起來,生成一個新的Animation對象。
CurvedAnimation源碼如下:
class CurvedAnimation extends Animation<double> with AnimationWithParentMixin<double> {
CurvedAnimation({
// 通常傳入一個AnimationController
@required this.parent,
// Curve類型的對象
@required this.curve,
this.reverseCurve,
});
}
Curve類型的對象的有一些常量Curves(和Color類型有一些Colors是一樣的),可以供我們直接使用:
- 對值的效果,可以直接查看官網(wǎng)(有對應(yīng)的gif效果,一目了然)
- https://api.flutter.dev/flutter/animation/Curves-class.html
官方也給出了自己定義Curse的一個示例:
import 'dart:math';
class ShakeCurve extends Curve {
@override
double transform(double t) => sin(t * pi * 2);
}
1.4. Tween
默認(rèn)情況下,AnimationController動畫生成的值所在區(qū)間是0.0到1.0,如果希望使用這個以外的值,或者其他的數(shù)據(jù)類型,就需要使用Tween。
Tween的源碼非常簡單,傳入兩個值即可,可以定義一個范圍,如下:
class Tween<T extends dynamic> extends Animatable<T> {
Tween({ this.begin, this.end });
}
Tween也有一些子類,比如ColorTween、BorderTween,可以針對動畫或者邊框來設(shè)置動畫的值。
要使用Tween對象,需要調(diào)用Tween的animate()方法,傳入一個Animation對象。
二. 動畫案例練習(xí)
2.1. 動畫的基本使用
我們來完成一個案例:
- 點擊案例后執(zhí)行一個心跳動畫,可以反復(fù)執(zhí)行
- 再次點擊可以暫停和重新開始動畫
import 'dart:async';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue, splashColor: Colors.transparent),
home: HYHomePage(),
);
}
}
class HYHomePage extends StatefulWidget {
@override
_HYHomePageState createState() => _HYHomePageState();
}
class _HYHomePageState extends State<HYHomePage>
with SingleTickerProviderStateMixin {
// 創(chuàng)建AnimationController
AnimationController _controller;
Animation _animation;
Animation _sizeAnim;
// bool _isForward;
@override
void initState() {
super.initState();
// 1.創(chuàng)建AnimationController
// 只有在方法里面才能寫this
_controller = AnimationController(
vsync: this,
duration: Duration(seconds: 2)
);
// 2.設(shè)置Curve的值
_animation = CurvedAnimation(parent: _controller, curve: Curves.linear);
// 3.Tween 設(shè)置范圍
_sizeAnim = Tween(begin: 50.0, end: 150.0).animate(_animation);
// 監(jiān)聽動畫值的改變,這時候_sizeAnim.value的值是一直改變的
// 值改變后我們就調(diào)用setState,調(diào)用setState之后就會重新執(zhí)行build,這時候界面上就有動畫效果了
_controller.addListener(() {
setState(() {});
});
// 監(jiān)聽動畫的狀態(tài)改變
// 狀態(tài)改變后反轉(zhuǎn),實現(xiàn)心跳效果
_controller.addStatusListener((status) {
if (status == AnimationStatus.completed) {
_controller.reverse();
} else if (status == AnimationStatus.dismissed) {
_controller.forward();
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("首頁"),
),
body: Center(
// 心形
child: Icon(Icons.favorite, color: Colors.red, size: _sizeAnim.value,),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.play_arrow),
onPressed: () {
// 如果動畫在執(zhí)行,就暫停
if (_controller.isAnimating) {
_controller.stop();
print(_controller.status);
// 如果是暫停后的向前狀態(tài),就繼續(xù)向前
} else if (_controller.status == AnimationStatus.forward) {
_controller.forward();
// 如果是暫停后的向后狀態(tài),就繼續(xù)向后
} else if (_controller.status == AnimationStatus.reverse) {
_controller.reverse();
} else {
// completed狀態(tài)直接開始
_controller.forward();
}
},
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}
/**
* 1.Animation: 抽象類
* * 監(jiān)聽動畫值的改變
* * 監(jiān)聽動畫狀態(tài)的改變
* * value
* * status
* 2.AnimationController繼承自Animation
* * vsync: 同步信號(this -> with SingleTickerProviderStateMixin)
* * forward(): 向前執(zhí)行動畫
* * reverse(): 反轉(zhuǎn)執(zhí)行動畫
* 3.CurvedAnimation:
* * 作用: 設(shè)置動畫執(zhí)行的速率(速度曲線)
* 4.Tween: 設(shè)置動畫執(zhí)行的value范圍
* * begin: 開始值
* * end: 結(jié)束值
*/
2.2. AnimatedWidget
在上面的代碼中,我們必須監(jiān)聽動畫值的改變,并且改變后需要調(diào)用setState,這會帶來兩個問題:
- 每次寫動畫都要寫一大段監(jiān)聽動畫值的改變代碼
- 調(diào)用setState意味著整個State類中的build方法就會被重新build
如何優(yōu)化上面的操作呢?創(chuàng)建一個Widget繼承于AnimatedWidget:
class HYAnimatedIcon extends AnimatedWidget {
// final Animation _sizeAnim;
//必須將_sizeAnim傳遞給父類
HYAnimatedIcon(Animation anim): super(listenable: anim);
@override
Widget build(BuildContext context) {
// listenable是父類的屬性
Animation anim = listenable;
return Icon(Icons.favorite, color: Colors.red, size: anim.value,);
}
}
詳細(xì)代碼如下:
import 'dart:async';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue, splashColor: Colors.transparent),
home: HYHomePage(),
);
}
}
class HYHomePage extends StatefulWidget {
@override
_HYHomePageState createState() => _HYHomePageState();
}
class _HYHomePageState extends State<HYHomePage>
with SingleTickerProviderStateMixin {
// 創(chuàng)建AnimationController
AnimationController _controller;
Animation _animation;
Animation _sizeAnim;
// bool _isForward;
@override
void initState() {
super.initState();
// 1.創(chuàng)建AnimationController
_controller = AnimationController(
vsync: this,
duration: Duration(seconds: 2)
);
// 2.設(shè)置Curve的值
_animation = CurvedAnimation(parent: _controller, curve: Curves.linear);
// 3.Tween
_sizeAnim = Tween(begin: 50.0, end: 150.0).animate(_animation);
// 監(jiān)聽動畫值的改變
// _controller.addListener(() {
// setState(() {});
// });
// 監(jiān)聽動畫的狀態(tài)改變
_controller.addStatusListener((status) {
if (status == AnimationStatus.completed) {
_controller.reverse();
} else if (status == AnimationStatus.dismissed) {
_controller.forward();
}
});
}
@override
Widget build(BuildContext context) {
print("執(zhí)行_HYHomePageState的build方法");
return Scaffold(
appBar: AppBar(
title: Text("首頁"),
),
body: Center(
// 將_sizeAnim傳進(jìn)去
child: HYAnimatedIcon(_sizeAnim),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.play_arrow),
onPressed: () {
if (_controller.isAnimating) {
_controller.stop();
print(_controller.status);
} else if (_controller.status == AnimationStatus.forward) {
_controller.forward();
} else if (_controller.status == AnimationStatus.reverse) {
_controller.reverse();
} else {
_controller.forward();
}
},
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}
但是AnimatedWidget也有缺點,如下:
- 我們每次都要新建一個類來繼承自AnimatedWidget
- 如果我們的動畫Widget有子Widget,那么意味著它的子Widget也會重新build
如何優(yōu)化上面的操作呢?AnimatedBuilder
2.3. AnimatedBuilder
import 'dart:async';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue, splashColor: Colors.transparent),
home: HYHomePage(),
);
}
}
class HYHomePage extends StatefulWidget {
@override
_HYHomePageState createState() => _HYHomePageState();
}
class _HYHomePageState extends State<HYHomePage>
with SingleTickerProviderStateMixin {
// 創(chuàng)建AnimationController
AnimationController _controller;
Animation _animation;
Animation _sizeAnim;
// bool _isForward;
@override
void initState() {
super.initState();
// 1.創(chuàng)建AnimationController
_controller = AnimationController(
vsync: this,
duration: Duration(seconds: 2)
);
// 2.設(shè)置Curve的值
_animation = CurvedAnimation(parent: _controller, curve: Curves.linear);
// 3.Tween
_sizeAnim = Tween(begin: 50.0, end: 150.0).animate(_animation);
// 監(jiān)聽動畫值的改變
// _controller.addListener(() {
// setState(() {});
// });
// 監(jiān)聽動畫的狀態(tài)改變
_controller.addStatusListener((status) {
if (status == AnimationStatus.completed) {
_controller.reverse();
} else if (status == AnimationStatus.dismissed) {
_controller.forward();
}
});
}
@override
Widget build(BuildContext context) {
print("執(zhí)行_HYHomePageState的build方法");
return Scaffold(
appBar: AppBar(
title: Text("首頁"),
),
body: Center(
child: AnimatedBuilder(
animation: _controller,
builder: (ctx, child) {
// 如果有child,就把下面的child放到這里,這個語法在consumer里面也講過
// 這樣寫可以解決第二個問題:子widget的child不會重新構(gòu)建
return Icon(Icons.favorite, color: Colors.red, size: _sizeAnim.value);
},
// child: {},
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.play_arrow),
onPressed: () {
if (_controller.isAnimating) {
_controller.stop();
print(_controller.status);
} else if (_controller.status == AnimationStatus.forward) {
_controller.forward();
} else if (_controller.status == AnimationStatus.reverse) {
_controller.reverse();
} else {
_controller.forward();
}
},
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}
三. 其它動畫補充
3.1. 交織動畫
案例說明:
- 點擊floatingActionButton執(zhí)行動畫;
- 動畫集合了透明度變化、大小變化、顏色變化、旋轉(zhuǎn)動畫等;
- 我們這里是通過多個Tween生成了多個Animation對象;
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue, splashColor: Colors.transparent),
home: HYHomePage(),
);
}
}
class HYHomePage extends StatefulWidget {
@override
_HYHomePageState createState() => _HYHomePageState();
}
class _HYHomePageState extends State<HYHomePage>
with SingleTickerProviderStateMixin {
// 創(chuàng)建AnimationController
AnimationController _controller;
Animation _sizeAnim;
Animation _colorAnim;
Animation _opacityAnim;
Animation _radiansAnim;
@override
void initState() {
super.initState();
// 1.創(chuàng)建AnimationController
_controller = AnimationController(
vsync: this,
duration: Duration(seconds: 2)
);
// 3.Tween
// 3.1.創(chuàng)建size的tween
_sizeAnim = Tween(begin: 10.0, end: 200.0).animate(_controller);
// 3.2.創(chuàng)建color的tween
_colorAnim = ColorTween(begin: Colors.orange, end: Colors.purple).animate(_controller);
// 3.3.創(chuàng)建opacity的tween
_opacityAnim = Tween(begin: 0.0, end: 1.0).animate(_controller);
// 3.4.創(chuàng)建radians的tween
_radiansAnim = Tween(begin: 0.0, end: 2 * pi).animate(_controller);
// 監(jiān)聽動畫的狀態(tài)改變
_controller.addStatusListener((status) {
if (status == AnimationStatus.completed) {
_controller.reverse();
} else if (status == AnimationStatus.dismissed) {
_controller.forward();
}
});
}
@override
Widget build(BuildContext context) {
print("執(zhí)行_HYHomePageState的build方法");
/**
* 1.大小變化動畫
* 2.顏色變化動畫
* 3.透明度變化動畫
*/
return Scaffold(
appBar: AppBar(
title: Text("首頁"),
),
body: Center(
// 使用AnimatedBuilder
child: AnimatedBuilder(
animation: _controller,
builder: (ctx, child) {
return Opacity(
// 不透明度,1不透明,0完全透明
opacity: _opacityAnim.value,
child: Transform(
transform: Matrix4.rotationZ(_radiansAnim.value),
// 設(shè)置沿著中心點旋轉(zhuǎn)
alignment: Alignment.center,
child: Container(
width: _sizeAnim.value,
height: _sizeAnim.value,
color: _colorAnim.value,
),
),
);
},
)
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.play_arrow),
onPressed: () {
if (_controller.isAnimating) {
_controller.stop();
print(_controller.status);
} else if (_controller.status == AnimationStatus.forward) {
_controller.forward();
} else if (_controller.status == AnimationStatus.reverse) {
_controller.reverse();
} else {
_controller.forward();
}
},
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}
3.2. Hero動畫
移動端開發(fā)經(jīng)常會遇到類似這樣的需求:
- 點擊一個頭像,顯示頭像的大圖,并且從原來圖像的Rect到大圖的Rect
- 點擊一個商品的圖片,可以展示商品的大圖,并且從原來圖像的Rect到大圖的Rect
在Flutter中,有一個專門的Widget可以來實現(xiàn)這種動畫效果:Hero
實現(xiàn)Hero動畫,需要如下步驟:
- 在第一個Page1中,定義一個起始的Hero Widget,被稱之為source hero,并且綁定一個tag;
- 在第二個Page2中,定義一個終點的Hero Widget,被稱之為 destination hero,并且綁定相同的tag;
- 可以通過Navigator來實現(xiàn)第一個頁面Page1到第二個頁面Page2的跳轉(zhuǎn)過程;
首頁Page代碼:
import 'package:flutter/material.dart';
import 'package:learn_flutter/_12_animation/pages/image_detail.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue, splashColor: Colors.transparent),
home: HYHomePage(),
);
}
}
class HYHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("首頁"),
),
body: Center(
child: GridView(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
childAspectRatio: 16/9
),
children: List.generate(20, (index) {
final imageURL = "https://picsum.photos/500/500?random=$index";
// 添加手勢
return GestureDetector(
onTap: () {
// 使用漸變的方式顯示界面
Navigator.of(context).push(PageRouteBuilder(
pageBuilder: (ctx, anim1, anim2) {
return FadeTransition(opacity: anim1, child: HYImageDetailPage(imageURL));
}
));
},
child: Hero(
// 將圖片地址作為tag,就能做到圖片放大的效果
tag: imageURL,
child: Image.network(
imageURL,
fit: BoxFit.cover,
),
)
);
}),
),
),
);
}
}
大圖展示頁面,image_detail.dart文件,代碼如下:
import 'package:flutter/material.dart';
class HYImageDetailPage extends StatelessWidget {
final String _imageURL;
HYImageDetailPage(this._imageURL);
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
body: Center(
child: GestureDetector(
onTap: () {
// 點擊大圖消失
Navigator.of(context).pop();
},
// 將圖片地址作為tag,就能做到圖片放大的效果
child: Hero(tag: _imageURL, child: Image.network(_imageURL))
),
),
);
}
}