【发布时间】:2018-11-01 13:22:09
【问题描述】:
在 Flutter 框架中通过扩展 AnimatedWidget 类实现了一个简单的改变颜色的动画小部件。小部件动画完成后怎么可能运行一个函数?
【问题讨论】:
在 Flutter 框架中通过扩展 AnimatedWidget 类实现了一个简单的改变颜色的动画小部件。小部件动画完成后怎么可能运行一个函数?
【问题讨论】:
你可以简单地做:
_controller.forward().then((value) => {
//run code when end
});
这会向前运行动画(您可以使用reverse 或任何其他模式)并在结束时调用//run code when end。
根据官方文档,.forward():
Returns a [TickerFuture] that completes when the animation is complete.
因此,使用Future api 的then 而不是_controller.forward() 返回的TickerFuture,您可以在动画完成时执行任何代码。
【讨论】:
你也可以使用这个:
_animationController.forward().whenComplete(() {
// put here the stuff you wanna do when animation completed!
});
【讨论】:
您可以收听AnimationController 的状态:
var _controller = new AnimationController(
0.0,
const Duration(milliseconds: 200),
);
_controller.addStatusListener((status) {
if(status == AnimationStatus.completed) {
// custom code here
}
});
Animation<Offset> _animation = new Tween<Offset>(
begin: const Offset(100.0, 50.0),
end: const Offset(200.0, 300.0),
).animate(_controller);
【讨论】:
_controller.addStatusListener((status) { if(status == AnimationStatus.completed) { // Getting control inside this check multiple times. //Code here needs to be executed exactly once, only after the entire animation is completed // What should be done to achieve this? } });
AnimationStatus.completed 之后你会得到什么 status?您可以随时在小部件顶部添加另一个标志,例如 if(status == AnimationStatus.completed && !isRunOnce) { isRunOnce = true; } 和 bool isRunOnce = false;。