Sobes.tech
Junior — Middle

How to control animation through AnimationController in your application?

sobes.tech AI

Answer from AI

In Flutter, the AnimationController class is used to manage animations. It allows you to start, stop, repeat, and control the progress of an animation.

Main steps:

  1. Create an AnimationController in the widget's state (usually in the initState method), specifying the duration of the animation and vsync (for resource optimization).
  2. Use the controller's methods: forward(), reverse(), repeat(), stop() to control the animation.
  3. Subscribe to animation value changes via a listener (addListener) to update the UI.
  4. Don't forget to free resources by calling dispose() on the controller in the widget's dispose method.

Example:

class MyAnimatedWidgetState extends State<MyAnimatedWidget> with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )..addListener(() {
        setState(() {}); // update UI on animation change
      });
    _controller.forward(); // start animation
  }

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

  @override
  Widget build(BuildContext context) {
    return Opacity(
      opacity: _controller.value, // value from 0.0 to 1.0
      child: YourWidget(),
    );
  }
}