Sub topic 18
Choosing the right approach
This chapter assumes you know AnimatedContainer, TweenAnimationBuilder, AnimationController, Tween, CurvedAnimation, AnimatedBuilder and Interval. It also assumes you can write a StatefulWidget with setState and a State that uses a ticker mixin. Here you learn how to pick among them, so you don't have to remember each API in isolation.
The deciding question
Ask who owns the animation's timeline.
- If the target value comes from state and Flutter can run the motion by itself, use an implicit animation.
- If your code must start, stop, repeat, reverse, scrub or synchronize the motion, use an explicit animation.
Everything else follows from this. An implicit widget owns its controller internally and only exposes a target value, a duration and a curve. An explicit animation hands you the controller, and with it the responsibility for creating and disposing it.
Comparison
| Concern | Implicit | Explicit |
|---|---|---|
| Who owns the controller | The framework | You |
| Trigger | Change a property and rebuild | Call `forward`, `reverse`, `repeat`, `animateTo` |
| Boilerplate | A duration and a curve | Mixin, controller, `dispose`, often a `Tween` |
| Looping | Awkward | `repeat`, with or without `reverse` |
| Several effects on one clock | Not supported | One controller with `Interval`s |
| Pause or scrub | Not supported | `stop`, `value`, `animateTo` |
| Typical bug | Forgetting that the first build does not animate | Forgetting `dispose` |
The same effect, both ways
A fade between two states is a good test. The implicit version needs no controller.
import 'package:flutter/material.dart';
class FadeNotice extends StatefulWidget {
const FadeNotice({super.key});
@override
State<FadeNotice> createState() => _FadeNoticeState();
}
class _FadeNoticeState extends State<FadeNotice> {
bool _visible = true;
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
AnimatedOpacity(
opacity: _visible ? 1 : 0,
duration: const Duration(milliseconds: 300),
child: const Text('Saved'),
),
TextButton(
onPressed: () => setState(() => _visible = !_visible),
child: const Text('Toggle'),
),
],
);
}
}The explicit version produces the same visual result with more code.
import 'package:flutter/material.dart';
class FadeNoticeExplicit extends StatefulWidget {
const FadeNoticeExplicit({super.key});
@override
State<FadeNoticeExplicit> createState() => _FadeNoticeExplicitState();
}
class _FadeNoticeExplicitState extends State<FadeNoticeExplicit>
with SingleTickerProviderStateMixin {
late final AnimationController _controller = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 300),
value: 1,
);
@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 Text('Saved'),
),
TextButton(onPressed: _toggle, child: const Text('Toggle')),
],
);
}
}The explicit version gains nothing here, and it adds a mixin, a dispose method and manual direction logic. For a one-way move to a new value, the implicit version is the better choice.
When explicit is the right answer
Move to an explicit animation when you see one of these requirements.
- The motion repeats or loops. The pulsing logo is the standard case:
repeat(reverse: true)is one call, and implicit widgets have no equivalent. - The motion starts without a state change. Examples are an entrance animation in
initStateor a spinner that runs while a request is pending. - Several properties share one timeline. One controller with
Intervals keeps the fade and the slide in lockstep, as in the staggered entrance. - You react to progress. A
StatusListenercan run code at completion, and the controller'svaluecan drive other logic. - A gesture drives the value. Dragging a sheet or scrubbing a timeline means assigning
controller.valuedirectly.
The middle ground
Prefer TweenAnimationBuilder when no built-in widget animates your property but the motion is still "go to the new value". It animates from the current value when end changes, so interrupted animations stay smooth. It also needs no controller or disposal. Examples are a rotation angle, a color filter strength or a custom painter parameter.
Common errors
Chaining implicit animations with onEnd
Implicit widgets accept an onEnd callback. Developers sometimes use it to flip state again and fake a loop.
Expecting the first frame to animate
An implicit widget animates only when a property changes between builds. If the widget is built with its final values, nothing moves. To animate on entry, either start TweenAnimationBuilder with a different begin and end, or use an explicit controller started in initState.
Forgetting disposal or the ticker mixin
Every explicit controller needs dispose(). Use SingleTickerProviderStateMixin for one controller. If a State creates more than one, switch to TickerProviderStateMixin, because the single-ticker mixin throws when asked for a second ticker.
Rebuilding too much on every tick
With AnimatedBuilder, pass the static subtree through the child parameter so only the animated wrapper rebuilds. Calling setState from a controller listener rebuilds the entire State's subtree on every frame, so avoid it for animation.
Cost and testing
Both approaches use the same underlying machinery: a ticker fires on each frame and a controller maps elapsed time to a value. The cost difference comes from rebuild scope, not from the animation engine. A coarse implicit widget high in the tree can be more expensive than a small, well-scoped AnimatedBuilder. Keep the animated widget as small as possible and hoist static children.
In widget tests, call tester.pump(duration) to advance an animation by a fixed time. Use pumpAndSettle() only when the animation ends. A repeating controller never settles, so pumpAndSettle() times out.
Exercises
Exercise
A badge must fade in when a message count becomes nonzero and fade out when it returns to zero. Which approach do you choose, and why?
Show answer
An implicit animation, specifically AnimatedOpacity. The motion is a one-way move to a new value driven by state, a built-in widget covers the property, and no controller or disposal is needed.
Exercise
A loading indicator must pulse continuously while a request is running, and stop when it finishes. Which approach fits, and which controller methods do you use?
Show answer
An explicit animation. Create an AnimationController with a ticker mixin, call repeat(reverse: true) when loading starts and stop (or reset) when it finishes, drive a ScaleTransition or FadeTransition from it, and dispose the controller. Implicit widgets cannot loop on their own.
Exercise
Why does a widget built with width 200 not animate to 200 on first display when it uses AnimatedContainer, and what are two ways to make it animate on entry?
Show answer
An implicit widget animates only when a property changes between builds, and on the first build the width is simply 200. Either build it with a starting value and change it after the first frame, or use TweenAnimationBuilder with different begin and end values, or start an explicit controller in initState.