【问题标题】:After complete the widget animation run a function in Flutter完成小部件动画后,在 Flutter 中运行一个函数
【发布时间】:2018-11-01 13:22:09
【问题描述】:

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

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    你可以简单地做:

    _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,您可以在动画完成时执行任何代码。

    【讨论】:

      【解决方案2】:

      你也可以使用这个:

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

      【讨论】:

        【解决方案3】:

        您可以收听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()?构建()?
        • _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 &amp;&amp; !isRunOnce) { isRunOnce = true; }bool isRunOnce = false;
        猜你喜欢
        • 1970-01-01
        • 2015-08-14
        • 1970-01-01
        • 1970-01-01
        • 2014-09-28
        • 1970-01-01
        • 2023-03-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多