AnimationController
- Flutter course
- Advanced
- Lesson 56/69
- 4 min
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();
}Practice Create an AnimationController
Define a class _EmptyVsync that implements TickerProvider. In main, create an AnimationController (vsync: _EmptyVsync(), duration 1 second) and print its value.
Starter code
import 'package:flutter/material.dart';
// _EmptyVsync sınıfını tanımla (TickerProvider uygular)
void main() {
// AnimationController oluştur (vsync ve duration 1 saniye) ve value değerini yazdır
}Sample 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();
}Expected output
0.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the vsync parameter of AnimationController do?
- Gives widget size
- Synchronizes animation updates every frame Correct answer
- It draws
- Sets color
Explanation: vsync provides a TickerProvider to the AnimationController so it updates every frame, producing smooth animation.
2 Add the vsync parameter
ctrl = AnimationController(
____: this,
duration: const Duration(seconds: 1),
);
ctrl = AnimationController(
vsync: this,
duration: const Duration(seconds: 1),
);
Explanation: The vsync parameter of AnimationController expects a TickerProvider; inside a State you pass this.
3 AnimationController parts
| Term | Meaning |
|---|---|
AnimationController |
Controls the animation |
vsync |
Frame provider |
SingleTickerProviderStateMixin |
vsync source |
forward |
Starts the animation |