插值器的作用主要是为动画提供每一帧的数值,通过将该数值设置给相应的视图(Widget)元素,从而实现动画效果。
常用的两类插值器:
Tween:线性插值器,能够自由设置起始值和结束值。
Curve:非线性插值器,默认情况下,起始值为 0.0,结束值为 1.0。
1.Tween
一个 Tween 插值器通过调用 animate()
传入一个 AnimationController,会返回一个 Animation 对象,我们从这个对象中可以取到其产生的值。
AnimationController animationController = new AnimationController(
vsync: this, duration: Duration(milliseconds: 800));
Animation<double> animation =
Tween<double>(begin: 0, end: 400.0).animate(animationController);
Tween 支持设置范型,比如上面的:Tween<double>
。
当然,所设的范型的类型需要有相应的 +
,-
运算符的定义,否则就会报错。
2.Curve
// 创建 AnimationController
var controller = AnimationController(
vsync: this, duration: Duration(milliseconds: duration));
// 创建 CurveAnimation
var anim = CurvedAnimation(parent: controller, curve: curve)
非线性插值器的用法和 Tween 不太一样,它是直接创建一个 CurvedAnimation 对象,然后传入一个 Curve。
Flutter 目前内置了多种线性插值器,它们的值变化都是 0.0 -> 1.0
, 比如:
更多的类型和效果,可以查看 Curve 类的说明。
2.1 自定义 Curve
如果 Flutter 提供的 Curve 类型插值器不够用,你可以自定义一个。
class _BounceInCurve extends Curve {
const _BounceInCurve._();
@override
double transform(double t) {
assert(t >= 0.0 && t <= 1.0);
return 1.0 - _bounce(1.0 - t);
}
}
很简单,关键就是重写 transform()
函数,在其中计算返回中间值。
⚠️ 注意,
transform()
中接收到的 t 的取值范围是 0 ~ 1。