完成Flutter小部件动画后运行函数

19

通过扩展AnimatedWidget类,在Flutter框架中实现了一个简单的动画小部件,可以改变颜色。在小部件动画运行完成后如何执行函数?

3个回答

35
你可以监听 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);

我不确定应该把这个放在哪里... initState()?build()? - jesses.co.tt
`_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? } });` - Febin K R
第一次完成动画后,您会得到什么“状态”? 您可以始终添加另一个标志,例如if(status == AnimationStatus.completed &&!isRunOnce){isRunOnce = true;},并在小部件顶部使用bool isRunOnce = false; - Günter Zöchbauer

24

你也可以使用这个:

_animationController.forward().whenComplete(() {
 // put here the stuff you wanna do when animation completed!
});

2
你可以简单地执行以下操作:
_controller.forward().then((value) => {
      //run code when end
});

这将使动画向前运行(您可以使用reverse或任何其他模式),并在结束时调用//run code when end。 根据官方文档,.forward()返回一个[TickerFuture],当动画完成时完成。

因此,使用_controller.forward()返回的TickerFuture上的Future API的then,您可以在动画完成时执行任何代码。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接