0
0
Fluttermobile~5 mins

AnimationController in Flutter

Choose your learning style9 modes available
Introduction

An AnimationController lets you create animations by controlling how they start, stop, and change over time.

When you want to animate a widget's size or color smoothly.
When you need to control animation speed or repeat it.
When you want to create custom animations beyond simple built-in ones.
Syntax
Flutter
AnimationController(
  vsync: this,
  duration: const Duration(seconds: 1),
);

vsync helps the animation run efficiently by syncing with the screen refresh.

duration sets how long the animation lasts.

Examples
Animation that lasts half a second.
Flutter
AnimationController(
  vsync: this,
  duration: const Duration(milliseconds: 500),
);
Animation that goes forward in 2 seconds and reverses in 1 second.
Flutter
AnimationController(
  vsync: this,
  duration: const Duration(seconds: 2),
  reverseDuration: const Duration(seconds: 1),
);
Sample App

This example creates a blue square that fades in and out continuously using AnimationController.

Flutter
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Scaffold(
        body: Center(
          child: SimpleAnimation(),
        ),
      ),
    );
  }
}

class SimpleAnimation extends StatefulWidget {
  const SimpleAnimation({super.key});

  @override
  State<SimpleAnimation> createState() => _SimpleAnimationState();
}

class _SimpleAnimationState extends State<SimpleAnimation> with SingleTickerProviderStateMixin {
  late final AnimationController _controller;

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

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

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        return Opacity(
          opacity: _controller.value,
          child: Container(
            width: 200,
            height: 200,
            color: Colors.blue,
          ),
        );
      },
    );
  }
}
OutputSuccess
Important Notes

Always dispose your AnimationController in the dispose() method to free resources.

Use SingleTickerProviderStateMixin to provide vsync for one AnimationController.

You can control the animation with methods like forward(), reverse(), and repeat().

Summary

AnimationController controls animation timing and progress.

It needs a vsync provider and a duration.

Dispose it properly to avoid memory leaks.