19

In Flutter framework by extending the AnimatedWidget class is implemented a simple animation widget that changes color. How is it possible after complete the widget animation run a function?

majidfathi69
  • 1,689
  • 2
  • 17
  • 24

3 Answers3

35

You can listen on the status of an 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);
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • i'm not entirely sure where to put this... initState()? build()? – jesses.co.tt Nov 10 '19 at 19:13
  • `_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 Nov 17 '20 at 17:52
  • What `status` do you get after the first `AnimationStatus.completed`? You can always add another flag like `if(status == AnimationStatus.completed && !isRunOnce) { isRunOnce = true; }` with `bool isRunOnce = false;` at the top of your widget. – Günter Zöchbauer Nov 18 '20 at 09:08
24

also you can use this :

_animationController.forward().whenComplete(() {
 // put here the stuff you wanna do when animation completed!
});
Mohad Hadi
  • 1,826
  • 3
  • 24
  • 39
2

You can simple do:

_controller.forward().then((value) => {
      //run code when end
});

This run the animation forward(you can use reverse or any other modes) and call to //run code when end when it end. Acording to official docs, .forward(): Returns a [TickerFuture] that completes when the animation is complete.

So using the then of the Future api over the TickerFuture returned in _controller.forward() you can execute any code when the animation completed.