how to dispose animation controller in flutter

Issue

I have a question like before disposing my controller do i need to call_controller.stop();

My code:-

AnimationController _controller;
@override
void initState()
{
    super.initState();
    _controller = AnimationController(duration: const Duration(milliseconds: 700), vsync: this);
    _controller.repeat(reverse: true);
    _controller.forward();
}

this animation is for showing a heart just like we tap on like on instagram and then heart increases its size and reduces.

code for tapping on heart button:-

onTap: ()=>controlUserLikePost(),

function:-

controlUserLikePost()
{
   _controller.reset();
   _controller.forward();
}

So, my question:-

@override
  void dispose()
  {
    _controller.stop();//do i need to call it as well?
    _controller.dispose();
    super.dispose();// and does it matter if i dispose the controller before this line or after this line.
  }

Solution

You don’t have to stop it before disposing it, unless you want to stop the animation at a certain point. But regarding disposing it safely, just use _controller.dispose().

However, it must be before the super.dispose(), not after, this is important.

Answered By – Huthaifa Muayyad

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.