Flutter的动画咱们要记住三个点,AnimationController、 Thween、Forward(),一个简单的动画就是由这三个组成的app
AnimationController:AnimationController用于控制动画,开始、反向播放、暂停等等都是由AnimationController来控制的,Controller会在每一帧都生成出一个新的值ide
AnimationController({
double value,
this.duration,
this.reverseDuration,
this.debugLabel,
this.lowerBound = 0.0,
this.upperBound = 1.0,
this.animationBehavior = AnimationBehavior.normal,
@required TickerProvider vsync,
})
复制代码
value:每一帧生成出来的值
duration:动画持续的时间
lowerBound、upperBound:生成出来的数字区间,AnimationController在动画期间会线性的生成出数字区间
vsync:接收一个TickerProvider,用来防止屏幕外动画(指动画不在屏幕内时-锁屏这也算)消耗没必要要的资源;Flutter在启动的时候会绑定一个SchedulerBinding,经过SchedulerBinding能够给每一次屏幕刷新一次回调,Ticker就是经过SchedulerBinding来添加屏幕刷新回调的,每次屏幕刷新都会调用到TickCallBack
简单的使用方法以下:咱们设定了一个10秒的动画控制器,我对vsync传入this是由于我with了SingleTickerProviderStateMixin动画
AnimationController controller= AnimationController(vsync: this,duration: Duration(seconds: 10));
复制代码
Tweed:咱们使用AnimationController能够线性的生成出一段数字区间,可是若是咱们要生成的是颜色呢?或者其余的呢?那咱们能够使用Tweed来作到了,Thweed除了数字外还有其余的子类能够供咱们使用,Tween若是要使用还须要调用animatie传入一个Animationui
注意:color的就用ColorTween,要对应上,若是想要设置Color,却用Tween,会报错this
Animation anmitiontween= ColorTween(begin:Colors.transparent,end:Colors.blue).animate(curved)..addListener((){
setState(() {
});
});
复制代码
具体有哪些能够用Tweed以下:
spa
Curve:动画的过程能够是匀速的,能够是加速,能够是减速,或者先加后减,或者先减后加等等,你想怎么玩就怎么玩,速度咱们都是能够经过CurvedAnimation来去设置他的曲线,Curve类给咱们提供了一些曲线,若是这其中不能知足咱们,咱们能够本身去自定义曲线,继承Curve,而后实现他的方法,返回一个doubledebug
CurvedAnimation curved=CurvedAnimation(parent: controller, curve: Curves.bounceIn);
//使用CurvedAnimation能够将一个Controller与curve结合起来生成一个新的动画对象
复制代码
class ShakeCurve extends Curve {
@override
double transform(double t) {
return math.sin(t * math.PI * 2);
}
}
复制代码
咱们在实际开发中,一些通用的动画最好抽取出来,作成AnimationUtils,避免写一些重复的动画代码
下面是一个颜色渐变的动画的核心代码code
AnimationController controller;
Animation anmitiontween;
CurvedAnimation curved;
@override
void initState() {
// TODO: implement initState
super.initState();
controller= AnimationController(vsync: this,duration: Duration(seconds: 5));
// curved=CurvedAnimation(parent: controller, curve: Curves.bounceIn);
anmitiontween= ColorTween(begin:Colors.transparent,end:Colors.red).animate(controller)..addListener((){
setState(() {
});
});
controller.forward();
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
title: Text("CCCC"),
),
body: Center(
child: GestureDetector(
child: Container(
width: 100.0,
height: 100.0,
child: Text("111"),
color: anmitiontween.value==null?Colors.transparent:anmitiontween.value,
),
),
),
);
}
@override
void dispose() {
// TODO: implement dispose
super.dispose();
controller.dispose();
}
复制代码
效果以下:
orm