创建
AnimationController的同时,也赋予了一个 vsync 参数。 vsync 的存在防止后台动画消耗不必要的资源。您可以通过添加SingleTickerProviderStateMixin到类定义,将有状态的对象用作 vsync
因为
addListener()函数调用setState(),所以每次Animation生成一个新的数字,当前帧就被标记为dirty,使得build()再次被调用。在build()函数中,container会改变大小,因为它的高和宽都读取animation.value,而不是固定编码值。当State对象销毁时要清除控制器以防止内存溢出。
class _AnimateContentState extends State<AnimateContent>
with SingleTickerProviderStateMixin {
bool flag = false;
late AnimationController _controller;
late Animation<double> animation;
@override
void initState() {
// TODO: implement dispose
super.initState();
_controller =
AnimationController(duration: const Duration(seconds: 1), vsync: this);
//animate() 方法会返回一个 Animation
animation = Tween<double>(begin: 0, end: 300).animate(_controller)
..addListener(() {
setState(() {});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
margin: const EdgeInsets.symmetric(vertical: 10),
width: animation.value,
height: animation.value,
child: const FlutterLogo(),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
_controller.forward();
},
child: const Icon(Icons.add),
),
);
}
@override
void dispose() {
// TODO: implement dispose
super.dispose();
}
}