Sub topic 1
How animation works in Flutter
Flutter has no special "animation mode". An animation is a widget tree that is rebuilt many times per second, with a value that changes a little on each rebuild. This chapter explains that model. The later chapters on implicit and explicit animations are tools built on top of it.
Prerequisites
This chapter assumes you already know:
- Dart basics: classes, mixins, generics and closures.
- How Flutter widgets and the
buildmethod work. StatelessWidgetandStatefulWidget, includingsetState.- Basic layout widgets such as
Container,RowandColumn.
Animation is a value that changes over time
Think of a flip book. Each page is a still picture, and the pictures differ slightly. Flipping fast enough makes your eyes see motion.
Flutter works the same way. Each still picture is a frame. A frame is one complete drawing of the screen. If a box is 100 pixels wide in one frame and 103 pixels wide in the next, the box looks like it is growing.
An animation therefore needs two things:
- A value that changes with time, such as a width, an opacity or an angle.
- A way to rebuild or repaint the UI each time that value changes.
The frame budget
A display refreshes at a fixed rate. Flutter tries to produce one new frame for each refresh. The time available for each frame is the frame budget.
| Refresh rate | Frame budget |
|---|---|
| 60 Hz | about 16.7 ms |
| 90 Hz | about 11.1 ms |
| 120 Hz | about 8.3 ms |
In that time Flutter must run your build methods, lay out the widgets and paint them. If the work takes longer than the budget, the frame is late. The user sees this as stutter, which developers call jank. Keep this budget in mind. Much of this tutorial is about doing less work on each frame.
Where frame callbacks come from
Flutter does not animate on a timer you set. The engine tells Flutter when the screen is ready for a new frame. This signal is called vsync, short for vertical synchronization. Flutter's scheduler then calls every callback registered for that frame.
A Ticker is an object that registers for these callbacks. On each frame it calls your function with the elapsed time, the time since the ticker started. Tickers sit at the bottom of every animation in Flutter. Every other animation class uses one underneath, directly or through other classes.
The loop looks like this:
Two properties of this loop matter:
- The value is computed from elapsed time, not from "how many frames have run". If one frame is late, the next frame jumps to the correct value. The animation takes the same total time on slow and fast devices. It only looks less smooth on the slow one.
- The loop only runs while something needs it. A ticker that is stopped asks for no frames, so an idle app uses almost no CPU.
A hand-built animation
The next example uses a Ticker directly. You will rarely do this in real code, because AnimationController wraps it. Writing it by hand shows that nothing else is going on.
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
void main() {
runApp(
const MaterialApp(
home: Scaffold(body: Center(child: FrameDemo())),
),
);
}
class FrameDemo extends StatefulWidget {
const FrameDemo({super.key});
@override
State<FrameDemo> createState() => _FrameDemoState();
}
class _FrameDemoState extends State<FrameDemo>
with SingleTickerProviderStateMixin {
late final Ticker _ticker;
Duration _elapsed = Duration.zero;
@override
void initState() {
super.initState();
_ticker = createTicker((elapsed) {
setState(() => _elapsed = elapsed);
})..start();
}
@override
void dispose() {
_ticker.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final seconds = _elapsed.inMicroseconds / Duration.microsecondsPerSecond;
// t runs from 0.0 to 1.0 every 2 seconds, then starts over.
final t = (seconds % 2) / 2;
return Container(
width: 50 + 150 * t,
height: 50,
color: Colors.teal,
);
}
}Follow one frame through the code:
- The engine signals vsync, and the ticker calls the closure with the elapsed time.
setStatestores the time and marks the widget as dirty.- Flutter calls
buildin the same frame. buildturns the elapsed time into a width between 50 and 200.- Flutter lays out and paints the new
Container.
The mixin SingleTickerProviderStateMixin makes the State object a ticker provider, so it can call createTicker. The dispose method stops the ticker. Tickers hold a reference to the state, so a ticker that is never disposed is a leak.
Normalizing, mapping and shaping
The example already does the three steps that every Flutter animation does:
- Normalize time. Convert elapsed time into a progress number from 0.0 to 1.0. Here that is
t. Flutter packages this step asAnimationController. - Shape the progress. Apply a curve so that motion speeds up or slows down. The example uses a straight line, which is called linear motion and looks mechanical. Curves are covered in a later chapter.
- Map the progress to a real value. The expression
50 + 150 * tturns 0..1 into a width between 50 and 200. Flutter packages this step asTween.
These three steps explain most of the class names you will meet. Controllers, curves and tweens are named parts of the code above.
Two ways to use the loop
Writing a ticker and setState by hand is verbose. Flutter offers two levels of help.
| Approach | You provide | Flutter handles |
|---|---|---|
| Implicit | The target value and a duration | The ticker, the controller, the tween and the cleanup |
| Explicit | The controller, the tween and the cleanup | Frame callbacks and rebuild scheduling |
With an implicit animation, you change a property and the widget animates from the old value to the new one. AnimatedContainer is the standard example. With an explicit animation, you create and drive an AnimationController yourself. This gives you control over starting, stopping, reversing and repeating, at the cost of more code and your own cleanup.
Common mistakes at this level
- Treating a late frame as a longer animation. Animations follow the clock, not the frame count. Do not count frames to measure animation progress.
- Rebuilding too much on each frame. The code above calls
setStateon aStatewhosebuildreturns one small widget, so rebuilding is cheap. If the samesetStatesat at the top of a large screen, every frame would rebuild the whole screen. Later chapters show howAnimatedBuilderlimits the rebuild to the part that moves. - Forgetting to dispose. Any object that holds a ticker must release it in
dispose. - Putting heavy work in
build. Parsing data or sorting lists inside abuildthat runs 60 times per second uses up the frame budget.
What comes next
The next chapters follow the dependency order of the tutorial. Implicit animations come first, because they hide the ticker, the controller and the tween. Explicit animations then expose those pieces one at a time, so you can see what the implicit widgets were doing for you.
Exercise
In the FrameDemo example, the device drops one frame and the next callback receives an elapsed time that is 30 ms later than the previous one instead of 16 ms. What does the box do, and why?
Show answer
The box jumps further in that frame, but it stays on the correct schedule. The width is computed from the elapsed time, not from a frame count, so the value matches the real clock time. The animation still takes 2 seconds per cycle, but it looks less smooth during the slow frame.
Exercise
Name the three steps that the line 50 + 150 * t and the expression (seconds % 2) / 2 perform together, and say which Flutter class later takes over each step.
Show answer
Normalizing time into a 0..1 progress value is done by (seconds % 2) / 2 and later taken over by AnimationController. Mapping progress to a real value is done by 50 + 150 * t and later taken over by Tween. The third step, shaping the progress with a curve, is absent here because the motion is linear. CurvedAnimation and Curves provide it later.