Sub topic 9
AnimationController
This chapter assumes you know Dart classes and mixins, StatefulWidget with setState, and the implicit animations from the earlier chapters. It covers AnimationController, the object at the center of every explicit animation.
What the controller is
An AnimationController is a number generator tied to the frame clock. Over a given duration, it produces a double that moves from 0.0 to 1.0. Flutter calls it once per frame, and each time the controller updates its value and notifies its listeners.
The controller knows nothing about widgets, sizes, or colors. It doesn't know what is being animated. Your code reads the number and maps it to something visible, which later chapters cover with Tween and AnimatedBuilder.
AnimationController extends Animation<double>. Anything that accepts an Animation<double> can therefore take a controller directly.
The frame loop
Each frame follows the same path:
- The engine signals that a new frame is due.
- The controller's ticker fires and passes the elapsed time.
- The controller turns elapsed time into a new
value. - The controller notifies its listeners.
- Widgets that listen rebuild or repaint with the new value.
Creating a controller
Two arguments matter most: vsync and duration. Pass vsync: this from a State that mixes in SingleTickerProviderStateMixin. The next chapter explains tickers and what vsync does, so for now treat it as required.
The example below prints the raw value and drives a progress bar from it. The listener calls setState on every tick, which is the simplest way to see the controller work.
import 'package:flutter/material.dart';
void main() => runApp(
const MaterialApp(
home: Scaffold(body: Center(child: ControllerDemo())),
),
);
class ControllerDemo extends StatefulWidget {
const ControllerDemo({super.key});
@override
State<ControllerDemo> createState() => _ControllerDemoState();
}
class _ControllerDemoState extends State<ControllerDemo>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 2),
)..addListener(() => setState(() {}));
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('value: ${_controller.value.toStringAsFixed(2)}'),
Text('status: ${_controller.status.name}'),
const SizedBox(height: 12),
LinearProgressIndicator(value: _controller.value),
const SizedBox(height: 12),
Row(
mainAxisSize: MainAxisSize.min,
children: [
ElevatedButton(
onPressed: _controller.forward,
child: const Text('Forward'),
),
const SizedBox(width: 8),
ElevatedButton(
onPressed: _controller.reverse,
child: const Text('Reverse'),
),
const SizedBox(width: 8),
ElevatedButton(
onPressed: _controller.reset,
child: const Text('Reset'),
),
],
),
],
),
);
}
}Three details matter here:
- The controller is
late finaland created ininitState. It lives as long as theStatedoes, andbuildnever creates it. - The controller moves at a constant rate. Halfway through the duration,
valueis0.5. Easing comes from curves, not from the controller. - Passing
_controller.forwardas a callback works, becauseforwardhas an optional named parameter and still matchesVoidCallback.
Constructor parameters
| Parameter | Default | Purpose |
|---|---|---|
| `vsync` | required | The `TickerProvider` that supplies the ticker. |
| `duration` | `null` | Time to run from `lowerBound` to `upperBound`. |
| `reverseDuration` | `null` | Time for the reverse run. When `null`, `duration` is used. |
| `lowerBound` | `0.0` | The value at the dismissed end. |
| `upperBound` | `1.0` | The value at the completed end. |
| `value` | `lowerBound` | The starting value. |
| `debugLabel` | `null` | A name that shows up in debug output. |
If you call forward() or reverse() while duration is null, a debug build asserts. Set a duration in the constructor, or use animateTo or animateBack with an explicit duration.
Status and value
The controller is always in one of four states, available as controller.status.
The helper getters isAnimating, isCompleted, and isDismissed wrap these states. A later chapter on playback control covers repeating and status listeners in detail.
You can also set value yourself. Doing so stops any running animation, jumps to the new number, and notifies listeners. The value is clamped to the bounds.
_controller.value = 0.5; // jump to the middle
_controller.reset(); // jump to lowerBound and stop
_controller.stop(); // freeze at the current valueforward(from: 0.3) first sets the value to 0.3 and then runs to the upper bound. It returns a TickerFuture that completes when the run finishes.
Custom bounds
The 0.0 to 1.0 range is a convention, not a rule. When the number you want is something like a percentage or a count, set the bounds directly.
import 'package:flutter/material.dart';
class CountUp extends StatefulWidget {
const CountUp({super.key});
@override
State<CountUp> createState() => _CountUpState();
}
class _CountUpState extends State<CountUp>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 3),
lowerBound: 0,
upperBound: 100,
)
..addListener(() => setState(() {}))
..forward();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Text('${_controller.value.round()}%');
}
}Be careful when you combine custom bounds with Tween or CurvedAnimation. Those expect a 0.0 to 1.0 input, so custom bounds usually mean you skip them. For most effects, keep the default bounds and map the result with a tween.
AnimationController.unbounded removes the clamp. It is meant for physics-based motion such as flings, which later work may touch. Ordinary UI animations should not need it.
Common errors
- A missing
vsync. The constructor will not compile without it. - Creating the controller in
build. Every rebuild makes a new controller and leaks the old one. - Forgetting
dispose. The ticker keeps running after the widget leaves the tree, and Flutter reports an error in debug mode. - Calling
forward()with no duration. This triggers an assertion. - Using a plain
Statewith theSingleTickerProviderStateMixin-free signature. There is no ticker provider to pass, sovsync: thisfails to compile.
Summary of the working model
- The controller emits a linear number over a duration, once per frame.
- It has a value, a status, and optional bounds.
- It does not draw anything. Something else listens and turns the number into pixels.
- Its owner creates it in
initStateand disposes it indispose.
Exercise
A controller is created with duration: Duration(seconds: 4), lowerBound: 10, and upperBound: 50, then forward() is called. What is value after 1 second, and what is status when the run ends?
Show answer
The controller moves linearly from 10 to 50, which is 40 units over 4 seconds, so 10 units per second. After 1 second the value is 20. When the run ends, the value is 50 and the status is AnimationStatus.completed.
Exercise
Why does creating an AnimationController inside build cause problems, and where should it be created and disposed instead?
Show answer
build can run many times, so each call would create a new controller and leave the previous one running with its ticker, which leaks resources and resets the animation. Create the controller once in initState of a State that mixes in a ticker provider, and call dispose() on it in the State's dispose() method.