Flutter 提供了 AnimatedWidget,用于简化动画。github
继承 AnimatedWidget 实现的 Widget,不须要再手动在 addListener()
添加的回调中调用 setState()
。bash
1.继承 AnimatedWidgetide
class AnimatedImage extends AnimatedWidget {
AnimatedImage({Key key, Animation<double> animation})
: super(key: key, listenable: animation);
Widget build(BuildContext context) {
final Animation<double> animation = listenable;
return Center(
child: SizedBox(
// 获取 Animation 中的值
width: animation.value,
height: animation.value,
child: Container(
color: Colors.lightBlue,
),
);
}
}
复制代码
关键点在于,实现 AnimatedWidget,而后在 build()
函数中建立视图。函数
经过 animation.value
直接得到结果,设置到视图属性上。post
2.使用实现好的 AnimatedWidget动画
class ScaleAnimationRoute extends StatefulWidget {
@override
_ScaleAnimationRouteState createState() => _ScaleAnimationRouteState();
}
class _ScaleAnimationRouteState extends State<ScaleAnimationRoute>
with SingleTickerProviderStateMixin {
Animation<double> animation;
AnimationController controller;
initState() {
super.initState();
// 建立 AnimationController
controller = AnimationController(
duration: const Duration(seconds: 3), vsync: this);
// 建立 Animation
animation = Tween(begin: 0.0, end: 300.0).animate(controller);
// 不须要再在 `addListener()` 添加的回调中调用 `setState()`
// 启动动画
controller.forward();
}
@override
Widget build(BuildContext context) {
// 把刚刚建立的 animation 传入
return AnimatedImage(animation: animation,);
}
dispose() {
controller.dispose();
super.dispose();
}
}
复制代码
你看,不须要再写 addListener
、setState
这些代码!ui
实际上也没省多少事,哈哈哈..this