Flutter
AnimationController
Control animations with AnimationController.
What is AnimationController?
AnimationController is the object that controls an animation's duration, progress, and start. It requires a vsync parameter, so the State class is used with SingleTickerProviderStateMixin. You set the duration with duration and start it with forward.
class _MyState extends State<MyWidget> with SingleTickerProviderStateMixin {
late AnimationController ctrl;
@override
void initState() {
ctrl = AnimationController(
vsync: this,
duration: const Duration(seconds: 1),
);
super.initState();
}
}
dispose and repeat
To prevent memory leaks, AnimationController must be closed in the dispose method. You can run a continuous loop with repeat or play in reverse with reverse. Its value is a double between 0.0 and 1.0.
@override
void dispose() {
ctrl.dispose();
super.dispose();
}
Exercise Create an AnimationController
Define a class _EmptyVsync that implements TickerProvider. In main, create an AnimationController (vsync: _EmptyVsync(), duration 1 second) and print its value.
Show example solution
import 'package:flutter/material.dart';
class _EmptyVsync implements TickerProvider {
@override
Ticker createTicker(TickerCallback onTick) => Ticker(onTick);
}
void main() {
final controller = AnimationController(
vsync: _EmptyVsync(),
duration: Duration(seconds: 1),
);
print(controller.value);
controller.dispose();
}
Test yourself
-
What does the vsync parameter of AnimationController do?
- Gives widget size
- Synchronizes animation updates every frame
- It draws
- Sets color
Show answer
Synchronizes animation updates every frame — vsync provides a TickerProvider to the AnimationController so it updates every frame, producing smooth animation.
-
Add the vsync parameter
ctrl = AnimationController(
____: this,
duration: const Duration(seconds: 1),
);
Show answer
ctrl = AnimationController(
vsync: this,
duration: const Duration(seconds: 1),
);
-
AnimationController parts
- AnimationController
- Controls the animation
- vsync
- Frame provider
- SingleTickerProviderStateMixin
- vsync source
- forward
- Starts the animation
Next lesson: Tween and CurvedAnimation