flutterdart

Repeating animations specific times e.g 20 times by Flutter


I have a simple animation :

  Animation<double> animation;
  Tween<double> tween = Tween(begin: 1, end: 1.15);
  AnimationController animationController;
  @override
  void initState() {
    super.initState();
    animationController =
        AnimationController(vsync: this, duration: Duration(milliseconds: 300));
    animation = animationController.drive(tween);
}

What i want ?

make this animation repeats e.g 20 times .

What i tried before posted this question ?

1- This method not have a parameter or way that makes me repeats this animation e.g 20 times.

it repeats and repeats and repeats forever :

    animationController.repeat();

2- Use simple loops . It hangs my app, it requires to stop entire application and rerun it to solve that hanging . It's seems that loops completely not dealing with futures :

                            do {
                              animationController.forward().then((x) {
                                animationController.reverse().then((x) {
                                  repeats++;
                                });
                              });
                            } while (repeats < 20);

3- Making int variable and add a listener ..etc,it's working , but seems that it's not the best way to do that matter :

  int repeats = 0;

    animation.addStatusListener((status) {
      if (repeats < 20) {
        if (status == AnimationStatus.completed) {
          animationController.reverse();
        } else if (status == AnimationStatus.dismissed) {
          animationController.forward();
        }
        repeats++;
      }    });

4- make chain of then . **No comment on it ** 😂😂😂 :

    animationController.forward().then((x) {
      animationController.reverse().then((x) {
        animationController.forward().then((x) {
          animationController.reverse().then((x) {
            animationController.forward().then((x) {
              animationController.reverse();
            });
          });
        });
      });
    });

Now , shortly how can i repeat animation 20 times


Solution

  • You can try it:

    5 - Use TickerFuture return from repeat, set timeout then stop animation.

     AnimationController _animationController;
    
      @override
      void initState() {
        super.initState();
        _animationController = AnimationController(
          vsync: this,
          duration: Duration(seconds: 3),
        );
    
        _animationController.addListener(() => setState(() {}));
        TickerFuture tickerFuture = _animationController.repeat();
        tickerFuture.timeout(Duration(seconds:  3 * 10), onTimeout:  () {
          _animationController.forward(from: 0);
          _animationController.stop(canceled: true);
        });
      }