了解过Android 开发的应该知道,在Android 中给控件设置属性动画还是比较麻烦的,而且多个属性动画一起设置的话更是麻烦,要写很多行代码。
那么在Flutter 中,给Widget 设置动画就完全不需要那么复杂。只需要使用 AnimatedContainer
就够了。
AnimatedContainer
看名字就应该知道,他是Container + Animation ,也就是带动画的容器。 AnimatedContainer
继承于 ImplicitlyAnimatedWidget
,我们点开父类的源码,可以看到类名上面的注释:
/// An abstract widget for building widgets that gradually change their /// values over a period of time. /// /// Subclasses' States must provide a way to visit the subclass's relevant /// fields to animate. [ImplicitlyAnimatedWidget] will then automatically /// interpolate and animate those fields using the provided duration and /// curve when those fields change.
简单翻译一下就是:
这个类是用来构建带动画的widget,可以在一段时间内改变其值。 子类必须提供一种方法来访问子类的相关字段以进行动画的处理,当这些字段发生变化的时候,ImplicitlyAnimatedWidget 将使用提供的 duration 和 curve 来自动设置动画。
说的很厉害,来个例子:
实现上图效果非常简单,逻辑代码根本没有,只需要定义好几个数值,随机就ok。
首先定义几个变量:颜色,位置,宽高和下标:
var _colors = [
Colors.red,
Colors.green,
Colors.amber,
Colors.blue,
Colors.deepPurple
];
var _alignments = [
Alignment.center,
Alignment.bottomLeft,
Alignment.bottomRight,
Alignment.topRight,
Alignment.topLeft,
];
double _weight = 400;
double _height = 400;
int index = 0;
然后我们定义一个方法,用来点击的时候调用,随机变换数值:
next() {
setState(() {
if(_weight == 400){
_weight -= 100;
_height -= 100;
}else {
_weight += 100;
_height += 100;
}
index = Random().nextInt(5);
});
}
最后我们写 build
方法来实现页面:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('AnimatedContainerDemo'),
),
body: Center( // 让View在中间
child: GestureDetector( // 手势识别控件,用来写点击事件
onTap: (){
setState(() {
next();
});
},
child: AnimatedContainer( // AnimatedContainer控件
width: _weight, //设置上变量里的宽高
height: _height,
curve: Curves.fastOutSlowIn, // 设置插值属性
duration: Duration(milliseconds: 500), // 设置时间
color: _colors[index], //设置颜色
alignment: _alignments[index], // 设置位置
child: Text(
'A',
style: TextStyle(color: Colors.white, fontSize: 50),
),
),
),
),
);
}
可以看到代码里非常简单,只是设置了一个AnimatedContainer Widget,把属性填上去。
这个时候和我们在 ImplicitlyAnimatedWidget
源码中看到的注释一样,只要有值发生了变化,那么 AnimatedContainer
就会自动设置插值属性来改变值,这样动画效果就出来了。
使用Flutter 提供的 AnimatedContainer 可以很方便的实现 Widget的动画效果,在做一些简单的动画时可以说是非常方便了。其实还有很多类似于 AnimatedContainer的 Widget,使用方法都类似,就不一一讲解了,如果有不知道在哪看的同学,请移步Flutter官网