Sub topic 2
Implicit animations: let Flutter do the work
This chapter assumes you can write a StatefulWidget, call setState, and read a build method. Earlier you saw that Flutter animates by rebuilding widgets many times per second with changing values. Here you will see how implicit animations hide that work from you.
The idea in one sentence
An implicit animation is a widget that you give a target value and a duration. When the target changes, the widget moves from the old value to the new one by itself.
You never create a controller, a ticker, or a listener. You change state and rebuild. The widget notices the difference and animates it.
The built-in implicit widgets all start with Animated. Examples are AnimatedContainer, AnimatedOpacity, AnimatedAlign, AnimatedPadding, and AnimatedPositioned. TweenAnimationBuilder lets you build your own. Later chapters cover each of them in detail.
A minimal example
This app fades a square in and out. The only animation code is the AnimatedOpacity widget.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: Scaffold(body: Center(child: FadeDemo()))));
}
class FadeDemo extends StatefulWidget {
const FadeDemo({super.key});
@override
State<FadeDemo> createState() => _FadeDemoState();
}
class _FadeDemoState extends State<FadeDemo> {
bool _visible = true;
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
AnimatedOpacity(
opacity: _visible ? 1.0 : 0.0,
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
onEnd: () => debugPrint('fade finished'),
child: Container(width: 120, height: 120, color: Colors.teal),
),
const SizedBox(height: 24),
ElevatedButton(
onPressed: () => setState(() => _visible = !_visible),
child: const Text('Toggle'),
),
],
);
}
}Tapping the button flips _visible and calls setState. The next build passes a different opacity. AnimatedOpacity compares it with the value it had before and fades between the two over 300 ms. When the fade finishes, onEnd runs.
What happens inside
Every built-in implicit widget extends ImplicitlyAnimatedWidget. Its state object, a subclass of ImplicitlyAnimatedWidgetState, owns an AnimationController and one or more tweens. You do not see them, but they exist.
The sequence on each rebuild is:
- Your
setStatecauses a rebuild, and the parent creates a new widget with new property values. - Flutter keeps the existing state object and calls
didUpdateWidgeton it. - The state compares each animated property with the target of its tween.
- If a property changed, the tween's
beginis set to the value currently on screen and itsendto the new target. - The controller restarts from zero. On every frame,
buildruns with the interpolated value.
Step 4 has a useful consequence. If the user taps again in the middle of an animation, the new tween starts from wherever the widget currently is. The motion redirects smoothly and does not jump back to the old start.
The first build does not animate
On the first build, the widget has no previous value to compare against. It shows the initial values immediately. Implicit widgets animate changes, not appearances. If you want an element to animate when it first shows up, you need a different technique, such as TweenAnimationBuilder or an explicit animation.
The two required decisions
Every implicit widget asks for two things.
| Parameter | Required | Meaning |
|---|---|---|
| `duration` | Yes | How long the animation takes from old value to new value |
| `curve` | No, defaults to `Curves.linear` | How progress is spread over that time |
| `onEnd` | No | Callback when an animation completes |
The next chapter covers duration and curves in depth. For now, remember that duration has no default. The compiler will tell you if you forget it.
What implicit animations can and cannot do
Implicit animations fit a specific shape of problem: one value changes from A to B in response to a state change. The widget decides how to get there.
They work well for:
- Showing and hiding an element with a fade.
- Resizing or recoloring a card when it is selected.
- Moving a widget to a new alignment or position.
- Expanding a panel by changing its height.
They are limited in these ways:
- You cannot pause, reverse, or repeat the animation on demand. You can only change the target.
- You cannot run an animation forever without changing state.
- You cannot coordinate several animations on one timeline.
- You cannot read the animation's progress from outside the widget.
When you need any of these, move to explicit animations. A later chapter helps you decide.
Common errors
Nothing animates
The most frequent cause is that the value never changes between builds. Check that setState actually updates the field the widget reads. A value that is recomputed to the same result each time will not animate.
A second cause is using the plain widget. Container jumps to new values. AnimatedContainer animates them.
The widget is rebuilt as a new element
An implicit widget animates only if Flutter reuses its state object. Flutter reuses it when the widget keeps the same type and the same key in the same place in the tree. If you give it a new Key on each rebuild, or if you swap it for a different widget type, Flutter creates a fresh state. A fresh state counts as a first build, so nothing animates.
// Wrong: a new key each build discards the state, so there is no animation.
AnimatedOpacity(
key: UniqueKey(),
opacity: _visible ? 1.0 : 0.0,
duration: const Duration(milliseconds: 300),
child: const FlutterLogo(size: 80),
)Animating a child instead of a property
AnimatedOpacity animates its own opacity. If you swap its child for a different widget, the new child appears at once. The animation applies only to the property that changed.
Expecting a result in the same frame
setState schedules a rebuild. It does not animate synchronously. Code that reads layout right after setState sees the old value.
Putting expensive work in the animated subtree
An implicit widget rebuilds its builder on every frame. Pass static content through the child parameter, which the widget does not rebuild. Keep the animated part small.
Summary of the working model
- Change state, rebuild, and the widget animates toward the new target.
- The framework keeps the state object, so the widget must keep its type and key.
- A mid-animation change restarts from the current on-screen value.
- The first build never animates.
- You control only the target,
duration,curve, andonEnd.
Exercise
A developer wraps a square in AnimatedContainer with a 500 ms duration and changes its width inside setState. The width changes, but it snaps instantly with no animation. The AnimatedContainer has key: UniqueKey(). What is wrong, and how do you fix it?
Show answer
UniqueKey() creates a new key on every build, so Flutter cannot match the new widget to the old one. It discards the old state object and builds a fresh one, which counts as a first build and shows the new width at once. Remove the key, or use a stable key such as a ValueKey that does not change between rebuilds.
Exercise
An AnimatedOpacity is halfway through fading from 1.0 to 0.0 when the user taps a button that sets the target back to 1.0. Where does the new animation start, and why?
Show answer
It starts from the current on-screen opacity, about 0.5. When the target changes, the widget sets the tween's begin to the value currently shown and its end to the new target, then restarts the controller. That makes the motion reverse smoothly and not jump to 0.0 or 1.0 first.