'Reverse widget animation on destroy

I'm trying to animate a widget when it's created and reverse the animation when it's destroyed, but can't figure out where should I call the reverse method. Here's how I managed to do it

class _MyAnimatedWidgetState extends State<MyAnimatedWidget>
    with SingleTickerProviderStateMixin {
  late AnimationController controller;
  late Animation<double> animation;
  @override
  void initState() {
    super.initState();
    controller = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 400));
    animation = Tween<double>(begin: 0, end: 1).animate(controller);
    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    return SizeTransition(
      axis: Axis.vertical,
      sizeFactor: animation,
      child: Container(
        height: 400,
        color: Colors.blue,
        width: double.infinity,
      ),
    );
  }

  @override
  void dispose() {
    controller.reverse();
    controller.dispose();
    super.dispose();
  }
}

The animation works well on creation, but the reverse method has no effect.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source