Flutter has four ways to animate, and the question that tells them apart is a single one:
who decides when the animation ends? With implicit animations, a
Duration that you write decides. With an AnimationController you always
decide, but you can also repeat and reverse. With a physics simulation you do not decide: mass,
stiffness and friction do. With a CustomPainter you are not animating, you are
drawing.
Choosing the wrong level is the most common way of writing thirty lines where five would do - or, the other way round, of getting a movement that looks fake. This article takes the four levels one by one, with the code and the criterion for discarding it.
The Dart code in this article was analyzed
The four examples were put into a real Flutter project and passed to the analyzer:
flutter analyze on Flutter 3.44.2 stable (revision
c9a6c48423) answers "No issues found!". They compile and use no
nonexistent or deprecated APIs. They were not run on a device: this machine has
no emulators configured, so the visual effect is for you to see.
1. Implicit animations: you change the state, the animation is already done
The widgets whose name starts with Animated share a behaviour: when one of their
properties changes value, instead of jumping to the new value they reach it gradually. You need
neither a controller nor a ticker.
AnimatedContainer: a card that opens on touch
class SchedaEspandibile extends StatefulWidget {
const SchedaEspandibile({super.key});
@override
State<SchedaEspandibile> createState() => _SchedaEspandibileState();
}
class _SchedaEspandibileState extends State<SchedaEspandibile> {
bool _aperta = false;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => setState(() => _aperta = !_aperta),
child: AnimatedContainer(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
height: _aperta ? 200 : 80,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: _aperta ? Colors.indigo.shade50 : Colors.grey.shade200,
borderRadius: BorderRadius.circular(_aperta ? 16 : 8),
),
child: const Text('Shipping details'),
),
);
}
}
There is no animation code: there is a bool and three ternary expressions. The
setState changes _aperta, the build reproduces an
AnimatedContainer with different values, and the widget interpolates by itself between
the old and the new. Height, colour and corner radius move together, in the declared 300
milliseconds.
Remove the duration line and the code does not compile: for these widgets the
duration is mandatory, and it is a good design choice, because it makes animating by accident
impossible. Replace AnimatedContainer with Container and the code keeps
working and the card opens abruptly - useful to see the difference.
curve is the part people underrate. With Curves.linear the movement has
constant speed and looks mechanical; Curves.easeInOut starts and ends gently, and it
is what the eye expects from a physical object. If the value looks wrong, before changing the
duration, change the curve.
The limit of this level is precise: the animation starts when the value changes, and you have no object to query. You cannot pause it, reverse it halfway, repeat it, or know when it has finished. The moment you need one of these things, you need the next level - and not before.
2. AnimationController: when you need the object
An AnimationController is a value that moves over time and that you own:
forward(), reverse(), repeat(), stop(). The
price is that it has to be created, connected to the frame cycle and destroyed.
class PulsanteVivo extends StatefulWidget {
const PulsanteVivo({required this.onPressed, super.key});
final VoidCallback onPressed;
@override
State<PulsanteVivo> createState() => _PulsanteVivoState();
}
class _PulsanteVivoState extends State<PulsanteVivo>
with SingleTickerProviderStateMixin {
late final AnimationController _controller = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 600),
)..repeat(reverse: true);
late final Animation<double> _scala = Tween<double>(begin: 1.0, end: 1.08)
.chain(CurveTween(curve: Curves.easeInOut))
.animate(_controller);
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ScaleTransition(
scale: _scala,
child: ElevatedButton(
onPressed: widget.onPressed,
child: const Text('Complete order'),
),
);
}
}
Four lines carry all the weight. with SingleTickerProviderStateMixin is what supplies
the vsync: without that mixin, vsync: this does not compile. The
vsync is there so that the controller hooks into the rhythm of the screen's frames and
stops when the screen is not visible - which is why a looping animation does not drain the
battery on a page covered by another.
_controller.dispose() in dispose() is not optional. The controller is
registered with the ticker provider: if you do not destroy it, it keeps receiving ticks after the
widget has left the tree, keeps the State alive and in debug mode Flutter reports a
leak. It is the most frequent mistake at this level.
repeat(reverse: true) is the reason a controller is needed here: it makes the value go
from 0 to 1 and then from 1 to 0, indefinitely. With an implicit widget this cannot be expressed,
because there is no one to ask "and now go back".
The chain Tween(...).chain(CurveTween(...)).animate(_controller) composes two
transformations: the Tween maps the controller's 0-1 range onto 1.0-1.08, that is the
scale, and the CurveTween applies the curve. The order matters: written this way, the
curve acts on the progress and then the result is mapped onto the scale. The value 1.08 is an 8
percent enlargement, chosen because it is noticeable without shifting the surrounding text - larger
enlargements on a looping button become annoying.
Finally ScaleTransition instead of an AnimatedBuilder: it does the same
thing with less code, and belongs to the family of *Transition widgets
(FadeTransition, SlideTransition, RotationTransition) that
take a ready-made Animation. You use AnimatedBuilder only when none of
these does what you need.
3. SpringSimulation: the duration is decided by physics
There is a class of movements that you cannot get with a fixed duration: those that depend on how the user let the object go. A card dragged and released slowly must return to its place differently from one that is flicked.
class SchedaMolla extends StatefulWidget {
const SchedaMolla({super.key});
@override
State<SchedaMolla> createState() => _SchedaMollaState();
}
class _SchedaMollaState extends State<SchedaMolla>
with SingleTickerProviderStateMixin {
// unbounded: the value can leave the 0-1 range
late final AnimationController _controller =
AnimationController.unbounded(vsync: this);
double _offset = 0;
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _rilascia(DragEndDetails d) {
final simulazione = SpringSimulation(
const SpringDescription(mass: 1, stiffness: 320, damping: 18),
_offset, // where it starts
0, // where it must arrive
d.velocity.pixelsPerSecond.dy, // with what initial velocity
);
_controller
..addListener(() => setState(() => _offset = _controller.value))
..animateWith(simulazione);
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onVerticalDragUpdate: (d) => setState(() => _offset += d.delta.dy),
onVerticalDragEnd: _rilascia,
child: Transform.translate(
offset: Offset(0, _offset),
child: const Card(child: SizedBox(height: 120, width: 240)),
),
);
}
}
Note that here there is no Duration, and it is not an oversight:
animateWith(simulazione) advances the controller until the simulation declares itself
at rest. How long it lasts depends on the parameters and on the initial velocity. It is the
conceptual difference from the two previous levels.
AnimationController.unbounded is mandatory in this context. The normal constructor
limits the value between lowerBound and upperBound (0 and 1 by default),
whereas here the value is a displacement in pixels that can be negative and can overshoot the target
in the bounce. With the bounded controller, the spring would be cut off at the edges.
The three numbers of SpringDescription are read like this: mass is the
inertia, stiffness how hard the spring pulls toward the target, damping
how much energy is lost. Their ratio decides the character of the movement: raise
stiffness and it becomes snappier, raise damping and it bounces less. With
damping too low it oscillates for a long time and looks like a toy; too high and the
spring cannot be told apart from any deceleration.
The fourth argument, d.velocity.pixelsPerSecond.dy, is what makes the gesture
believable: it passes to the simulation the velocity with which the finger left the screen. Put
0 in its place and the card would always return the same way, and a slow drag and a
violent one would give the same result - which is precisely what makes an animation look fake.
A warning about the code: addListener is called inside _rilascia, so if
the user drags many times, listeners accumulate. In a production version the listener should be
registered once in initState. I left it here because it keeps the block readable, but
it is a real defect and I prefer to say so than to let it be copied.
4. CustomPainter: when no widget draws what you want
The first three levels animate properties of existing widgets. The fourth is different: it gives
you a Canvas and the drawing primitives. You use it when the shape you need does not
exist as a widget - a chart, an arc indicator, a path.
class Ciambella extends StatelessWidget {
const Ciambella({required this.frazione, this.colore = Colors.indigo, super.key});
final double frazione; // 0.0 - 1.0
final Color colore;
@override
Widget build(BuildContext context) {
return CustomPaint(
size: const Size(120, 120),
painter: _CiambellaPainter(frazione: frazione, colore: colore),
child: Center(child: Text('${(frazione * 100).round()}%')),
);
}
}
class _CiambellaPainter extends CustomPainter {
_CiambellaPainter({required this.frazione, required this.colore});
final double frazione;
final Color colore;
@override
void paint(Canvas canvas, Size size) {
const spessore = 12.0;
final centro = size.center(Offset.zero);
final raggio = (size.shortestSide - spessore) / 2;
final binario = Paint()
..style = PaintingStyle.stroke
..strokeWidth = spessore
..color = colore.withValues(alpha: 0.15);
final arco = Paint()
..style = PaintingStyle.stroke
..strokeWidth = spessore
..strokeCap = StrokeCap.round
..color = colore;
canvas.drawCircle(centro, raggio, binario);
canvas.drawArc(
Rect.fromCircle(center: centro, radius: raggio),
-math.pi / 2, // start from 12 o'clock
2 * math.pi * frazione.clamp(0.0, 1.0), // sweep of the arc
false, // do not connect to the center
arco,
);
}
@override
bool shouldRepaint(_CiambellaPainter old) =>
old.frazione != frazione || old.colore != colore;
}
The paint method receives the Canvas and the actual Size,
and draws twice on the same circle: first the background track with drawCircle, then
the progress arc with drawArc. Neither primitive knows what a percentage is: the
translation lives in the arithmetic of the arguments.
The two numbers to understand are the angles. -math.pi / 2 is the starting angle, that
is minus ninety degrees, because on a canvas the zero angle points to the right and we want to start
at the top. 2 * math.pi * frazione is the sweep: the full turn multiplied by the
fraction. With frazione at 0.25 you get a quarter turn starting from 12 o'clock.
PaintingStyle.stroke is what makes the shape a donut and not a disc: it says to trace
the outline instead of filling. With the default value, PaintingStyle.fill,
drawCircle would draw a solid circle and the result would be a different chart.
strokeCap = StrokeCap.round rounds the ends of the arc, and applies only to the arc
because the background circle is closed.
shouldRepaint is the method people get wrong most often. It receives the previous
instance of the painter and must say whether something that influences the drawing has
changed. Always returning true repaints on every frame even when nothing has changed;
always returning false freezes the chart on the first value - and it is a bug that is
hard to understand, because the datum in the state is correct and the screen is not.
Note the child: inside CustomPaint: the text with the percentage is a
normal widget overlaid on the drawing, not something drawn on the canvas. Writing text with
TextPainter on the canvas is possible but awkward, and almost always the right solution
is this one - leave the text to widgets and use the canvas only for shapes.
Choosing the level: the criterion, not the list
Which level to use
- Implicit (
Animated*): a property changes and must get there gracefully - Explicit (
AnimationController): you need to repeat, reverse, pause, or know when it ends - Physical (
SpringSimulation,FrictionSimulation): the movement continues a user gesture - CustomPainter: the shape does not exist as a widget
- Hero: the same element must appear to pass from one screen to another
The five items are not alternatives of equal rank: they are in order of cost, and the rule is to stop at the first one that solves the problem. The criterion that separates them remains the one from the opening, that is who decides the end of the movement, and the line that is got wrong most often is the third - using a fixed duration where the user's gesture should determine it produces an animation that is correct but looks wrong. The last is the only one that is not about a single widget but about a transition between screens, so it does not compete with the others.
The percentages that the previous version of this article attached to the first two items ("90% of transitions", "80% of cases") have been removed: nobody counted, and an invented number does not help you choose any more than the criterion does.
What you can do now
You can recognize which of the four levels you need before writing code, connect a controller to the
ticker and destroy it, pass the velocity of a gesture to a simulation, and draw an arc knowing where
the angles start from. You also know the two lines that must not be forgotten:
dispose() on the controller and a well-written shouldRepaint.
Animations are also where the frame budget is spent: how to notice that one of these is causing half a page to be repainted is in Impeller, the rendering pipeline and jank. If instead you are interested in the mechanism that makes it cheap to rebuild a widget on every frame, it is explained in widget, element and render tree. Checking that an animation stays what you designed after a refactoring is the job of golden tests, and what drives the state changes that trigger implicit animations is state management, covered in Riverpod in depth. To bring the same animations to the browser, the compiler and the headers are in Flutter Web with WebAssembly.
Sources
- Flutter - Introduction to animations - the distinction between implicit and explicit animations and the criterion with which the documentation itself recommends choosing. Consulted on 2026-11-08.
-
Flutter
API -
ImplicitlyAnimatedWidget- the base class of theAnimated*widgets, hence the mandatoryduration. Consulted on 2026-11-08. -
Flutter API
-
AnimationController- the role ofvsync, theunboundedconstructor,repeat,animateWithand the obligation todispose. Consulted on 2026-11-08. -
Flutter API -
SpringDescriptionandSpringSimulation- the meaning ofmass,stiffnessanddampingand the order of the constructor arguments. Consulted on 2026-11-08. -
Flutter API -
CustomPainter- the contract ofpaintand the meaning ofshouldRepaint, including the consequence of always returning the same value. Consulted on 2026-11-08. -
Code verification - the four examples were analyzed with
flutter analyzeon Flutter 3.44.2 stable (revisionc9a6c48423) on 2026-11-08, result "No issues found!". No execution on a device or emulator.
All the entries are documentation and API reference of the Flutter project: for animations it is an almost obligatory choice, because parameter names and constructors change between versions and only the official reference follows the code. The code verification entry also declares what was not done, which here is the important part: a correct animation and a pleasant animation are two different judgements, and the second requires looking at it.
In this series, the previous article is Platform Channels: Integrating Swift and Kotlin Native Code.
Commenti
Caricamento commenti...
Sign in to comment