听一个动画完成

Bra*_*sen 7 animation dart flutter

我正在尝试在动画完成后执行一个操作。我尝试添加一个 statusListener 但这对我不起作用。我的代码如下所示:

  @override
  void initState() {
    super.initState();
    _controller = new AnimationController(
      duration: new Duration(milliseconds: 500),
      vsync: this,
    )..addStatusListener((AnimationStatus status) {
      print("Going");
      if (status.index == 3 && spins > 0) { // AnimationStatus index 3 == completed animation
        _controller.duration = new Duration(milliseconds: speed - 50);
        _controller.forward(from: _controller.value == null ? 0.0 : 1 - _controller.value);
        spins--;
        print(speed);
      }
    });
  }
Run Code Online (Sandbox Code Playgroud)

print(Going);永远不会被执行,但我的动画不结束。出了什么问题?

/// - -编辑 - -///

我正在使用AnimatedBuilder,那部分代码如下所示:

child: new AnimatedBuilder(
  animation: _controller,
  child: new Image.network(widget.url),
  builder: (BuildContext context, Widget child) {
    return new Transform.rotate(
      angle: _controller.value * 2.0 * math.PI,
      child: child,
    );
  },
),
Run Code Online (Sandbox Code Playgroud)

Rai*_*ann 10

对您的评论和编辑做出反应,我查看了 AnimationBuilder。修改文档中的示例我想出了这个工作解决方案:

class Spinner extends StatefulWidget {
  @override
  _SpinnerState createState() => new _SpinnerState();
}

class _SpinnerState extends State<Spinner> with SingleTickerProviderStateMixin {
  AnimationController _controller;
  CurvedAnimation _animation;

  @override
  void initState() {
    super.initState();
    _controller = new AnimationController(
      duration: const Duration(seconds: 5),
      vsync: this,
    )..forward();

    _animation = new CurvedAnimation(
        parent: _controller,
        curve: Curves.linear,
    )..addStatusListener((AnimationStatus status) {
      if (status == AnimationStatus.completed)
        print('completed');
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new AnimatedBuilder(
      animation: _animation,
      child: new Container(width: 200.0, height: 200.0, color: Colors.green),
      builder: (BuildContext context, Widget child) {
        return new Transform.rotate(
          angle: _controller.value * 2.0 * 3.1415,
          child: child,
        );
      },
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

如您所见,我将控制器用作动画的父级,而不是用作 AnimationBuilder 的动画。希望能帮助到你。


Chi*_*ong 5

您还可以使用whenComplete监听器

_animationController.forward().whenComplete((){
     //Trigger different responses, when animation is started at different places.
})
Run Code Online (Sandbox Code Playgroud)