当给定的Listenable的值改变时重新构建的部件。
但需要为某一个Widget实现动画时,更多的情况是无状态的Widget,此时使用 AnimatedWidget 即可实现动画,只需继承并实现build()函数即可。AnimatedWidget 主要通过 Listenable 来监听小部件动画,主要是 Animation 对象,也包括ChangeNotifier 和 ValueNotifier。
代码示例
这里我们直接贴出官方库的实例代码分析即可:代码中,绿色的 Container 容器动画会在 10 秒内从 0° 旋转到 360°,并且传入了动画控制器作为 listenable,可对动画进行复杂控制,Flutter 将此定义为显式动画,而隐式动画组件是只需提供给组件动画开始、结束值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| import 'dart:math' as math;
class SpinningContainer extends AnimatedWidget { const SpinningContainer({Key key, AnimationController controller}) : super(key: key, listenable: controller);
Animation<double> get _progress => listenable;
@override Widget build(BuildContext context) { return Transform.rotate( angle: _progress.value * 2.0 * math.pi, child: child: Container(width: 200.0, height: 200.0, color: Colors.green), )y; } }
@override void initState() { _controller = AnimationController( duration: const Duration(seconds: 10), vsync: this, )..repeat(); super.initState(); } SpinningContainer(controller: _controller);
|