Sub topic 8
Explicit animations: taking control
This chapter assumes you know how StatefulWidget, setState and build work, and that you have used AnimatedContainer or TweenAnimationBuilder. It introduces the explicit approach and the parts it is made of. Later chapters cover each part in detail.
What "explicit" means
An implicit animation hides its machinery. You change a property such as width, and the widget animates from the old value to the new one. You never see a clock, a controller, or a progress value.
An explicit animation exposes that machinery. You create an object that holds the animation's progress, and you decide when it starts, stops, reverses, or repeats. You also decide which widget properties it affects. The cost is more code and more responsibility, because you own the object's lifetime. The gain is that you can express motion that implicit widgets cannot.
The name is not about the widgets you use. FadeTransition is an explicit widget, but AnimatedOpacity is implicit. The distinction is who owns the controller: Flutter (implicit) or your State object (explicit).
The pieces of an explicit animation
An explicit animation is a small pipeline. Each stage has one job.
- Ticker. A callback source that fires once per rendered frame. Your
Stateobject provides one through a mixin such asSingleTickerProviderStateMixin. The controller'svsyncargument receives it. - AnimationController. An
Animation<double>that produces values from 0.0 to 1.0 over aduration. It has methods such asforward(),reverse(), andrepeat(). - CurvedAnimation. Wraps a parent animation and reshapes its progress with a
Curve, for exampleCurves.easeInOut. The output still runs from 0.0 to 1.0. - Tween. Short for "in-betweening". It converts the 0.0–1.0 range into the type you need, such as a
double,Offset,Color, orSize. - Consumer widget. A transition widget (
FadeTransition,ScaleTransition) or anAnimatedBuilder. It listens to the animation and rebuilds only the part of the tree that depends on it.
An AnimationController is itself an Animation<double>. For a 0-to-1 effect such as opacity, you can pass the controller straight to a widget with no tween.
A minimal example
This widget fades a logo in and out. The button reverses the direction of the controller wherever it currently is.
import 'package:flutter/material.dart';
class FadeToggle extends StatefulWidget {
const FadeToggle({super.key});
@override
State<FadeToggle> createState() => _FadeToggleState();
}
class _FadeToggleState extends State<FadeToggle>
with SingleTickerProviderStateMixin {
late final AnimationController _controller = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 300),
value: 1.0,
);
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _toggle() {
if (_controller.isForwardOrCompleted) {
_controller.reverse();
} else {
_controller.forward();
}
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
FadeTransition(
opacity: _controller,
child: const FlutterLogo(size: 80),
),
const SizedBox(height: 16),
ElevatedButton(onPressed: _toggle, child: const Text('Toggle')),
],
);
}
}Four things to notice:
- The mixin makes the
Stateobject aTickerProvider, sovsync: thisis valid. value: 1.0starts the controller at the end, so the logo is visible at first.buildnever callssetState.FadeTransitionlistens to the controller and repaints by itself.disposereleases the controller. Section "Ownership" below explains why.
Why not just call setState?
You could add a listener to the controller and call setState on every tick. That works, but it rebuilds the whole build method about 60 times a second, including children that never change. Explicit animation widgets avoid this. AnimatedBuilder and the transition widgets subscribe to the animation themselves and rebuild only their own subtree. The State object's build runs once.
What explicit animations can do that implicit ones cannot
Implicit widgets animate from the current value to a new target and then stop. Explicit animations cover cases outside that model:
| Requirement | Implicit | Explicit |
|---|---|---|
| Animate when a property changes | Yes | Yes |
| Loop forever or repeat back and forth | No | Yes, `repeat()` |
| Pause, resume, or stop at a given point | No | Yes, `stop()`, `animateTo()` |
| Run code when the animation finishes | Limited, `onEnd` | Yes, status listeners |
| Drive several properties from one clock | No | Yes |
| Sequence effects on one timeline | No | Yes, `Interval` |
| Tie progress to a gesture, such as a drag | No | Yes, set `value` directly |
If your effect appears in the first row only, choose an implicit widget. The final chapter of this tutorial gives decision criteria.
Ownership: you create it, you dispose it
An AnimationController registers a ticker with the framework's scheduler. If the widget leaves the tree and the controller stays alive, the ticker keeps running and holds references to your State object. In debug mode, Flutter throws an error when a State is disposed while its ticker is still active, with a message that includes "was disposed with an active Ticker".
The rule is simple:
- Create the controller in
initStateor in alate finalfield initializer. - Dispose it in
dispose, before callingsuper.dispose(). - Do not create a controller inside
build. Every rebuild would create a new one and leak the old one.
Use SingleTickerProviderStateMixin when the state has one controller. If you need two or more, use TickerProviderStateMixin.
Common errors
- Missing
vsync.AnimationControllerrequires it. Without the mixin,thisis not aTickerProviderand the code does not compile. - Wrong mixin. Using
SingleTickerProviderStateMixinwith two controllers fails at runtime with an error that a ticker was created more than once. - Forgetting
dispose. The animation seems to work, then the console reports a leaked ticker after the widget is removed. - Reading
controller.valueinbuildwithout a listener. The value is correct at that moment, but nothing triggers a rebuild when it changes. - Expecting values outside 0 to 1. The controller is bounded by default. Convert to other ranges with a
Tween, not by changing the controller's bounds.
Exercise
A teammate writes an AnimationController inside the build method of a StatefulWidget's state, calls forward() right after creating it, and passes it to a FadeTransition. Name two problems with this design and say where the controller should live.
Show answer
First, every rebuild of the widget creates a new controller that restarts from the beginning, so the animation resets whenever the parent rebuilds. Second, the old controllers are never disposed, so their tickers leak. The controller should be created once in initState (or a late final field initializer) in a state class that mixes in SingleTickerProviderStateMixin, and disposed in dispose.
Exercise
The FadeToggle example uses FadeTransition with the controller as its opacity, and build never calls setState. Why does the logo still fade?
Show answer
FadeTransition is an animated widget that subscribes to the Animation<double> it receives. On every tick it marks only its own render object for repaint, so the parent's build does not need to run.