Sub topic 4
Your first implicit animation: AnimatedContainer
This chapter assumes you know StatefulWidget and setState, the Container widget, and basic Dart (named parameters, ternary expressions, closures). You do not need any animation knowledge. By the end you will be able to animate a box with AnimatedContainer, say which properties it animates, and avoid its common errors.
What AnimatedContainer does
AnimatedContainer is a Container that animates between property values. You give it a target size, color, or padding. When the target changes on a later build, the widget moves from the old value to the new one over a duration you choose.
You never create a controller, a ticker, or a tween. Flutter creates and disposes them inside the widget. That is why this kind of animation is called implicit.
Two parameters matter first:
durationis required. It sets how long a transition takes.curveis optional. It sets how the motion speeds up and slows down. The default isCurves.linear.
A complete example
This app toggles a boolean on each tap. The boolean selects the target size and color.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: Center(child: GrowingBox()))));
class GrowingBox extends StatefulWidget {
const GrowingBox({super.key});
@override
State<GrowingBox> createState() => _GrowingBoxState();
}
class _GrowingBoxState extends State<GrowingBox> {
bool _big = false;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => setState(() => _big = !_big),
child: AnimatedContainer(
duration: const Duration(milliseconds: 400),
curve: Curves.easeInOut,
width: _big ? 200 : 100,
height: _big ? 200 : 100,
color: _big ? Colors.teal : Colors.orange,
),
);
}
}Run it and tap the box. It grows from 100 to 200 logical pixels and changes from orange to teal over 400 ms.
What happens on each tap
Your code only changes state. The animation machinery is inside AnimatedContainer.
Your build method runs once per setState, not once per frame. The widget's internal state object drives the per-frame rebuilds.
Which properties animate
AnimatedContainer accepts the same layout and paint properties as Container. These properties animate when their value changes:
| Property | Type | Notes |
|---|---|---|
| `width`, `height` | `double?` | Animated as numbers. |
| `color` | `Color?` | Blended channel by channel. |
| `decoration` | `Decoration?` | Border radius, borders, gradients, and shadows animate if both values are the same decoration type. |
| `foregroundDecoration` | `Decoration?` | Painted in front of the child. |
| `padding`, `margin` | `EdgeInsetsGeometry?` | Animated per edge. |
| `alignment` | `AlignmentGeometry?` | Moves the child within the box. |
| `constraints` | `BoxConstraints?` | Min and max sizes animate. |
| `transform` | `Matrix4?` | Animates scale, rotation, or translation. |
child is not animated. If you swap it for a different widget, the swap is instant. Use AnimatedSwitcher for that.
Animating shape with decoration
A plain color is limited. A BoxDecoration lets you animate corner radius, borders, and shadows together.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: Center(child: MorphingCard()))));
class MorphingCard extends StatefulWidget {
const MorphingCard({super.key});
@override
State<MorphingCard> createState() => _MorphingCardState();
}
class _MorphingCardState extends State<MorphingCard> {
bool _round = false;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => setState(() => _round = !_round),
child: AnimatedContainer(
duration: const Duration(milliseconds: 600),
curve: Curves.easeOutCubic,
width: 160,
height: 160,
padding: EdgeInsets.all(_round ? 32 : 8),
alignment: _round ? Alignment.center : Alignment.topLeft,
decoration: BoxDecoration(
color: _round ? Colors.indigo : Colors.amber,
borderRadius: BorderRadius.circular(_round ? 80 : 8),
boxShadow: [
BoxShadow(
blurRadius: _round ? 24 : 4,
color: Colors.black38,
),
],
),
child: const FlutterLogo(size: 40),
),
);
}
}Here one setState animates five properties at once. They all share the same duration and curve. If you need different timings per property, that calls for the explicit tools covered in later chapters.
Behavior to know
The first build does not animate. The widget starts at its initial values. Only later changes to the target produce motion. To animate on entry, build the widget with a starting value, then change state in a post-frame callback.
Interrupting restarts from the current value. If you tap during a transition, the widget does not jump. It starts a new transition from wherever the value is now to the new target. The new transition runs for the full duration again, so a reversal near the start of a transition can feel slower than expected.
Identical targets do nothing. If setState runs but the target values are equal to the previous ones, no animation starts.
Going from null to a value does not animate. If width is null in one build and 200 in the next, the widget snaps. It has no starting number to tween from. Give both states an explicit value. The same applies to decoration, padding, and the other properties.
Mixed decoration types can snap. Interpolating between two BoxDecoration objects works. Mixing a BoxDecoration with a ShapeDecoration has no defined in-between, so avoid it.
Common errors
- Setting both
coloranddecoration.Containerasserts that only one is set, andAnimatedContainerinherits the rule. Put the color inside theBoxDecorationas in the second example. - Forgetting
duration. It is a required parameter, so the code fails to compile. - Expecting size animation without a size. A
widthofnulllets the container take its size from its child or parent. That size is not a number the widget can tween. - Changing values without
setState. The widget only reacts to a rebuild with new arguments. Mutating a field withoutsetStateshows nothing. - Zero duration.
Duration.zeromakes the change instant.
Reacting to completion
onEnd runs when a transition finishes. Use it to chain state changes, such as flipping a flag to start the next step.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: Center(child: PingPong()))));
class PingPong extends StatefulWidget {
const PingPong({super.key});
@override
State<PingPong> createState() => _PingPongState();
}
class _PingPongState extends State<PingPong> {
bool _right = false;
@override
Widget build(BuildContext context) {
return SizedBox(
width: 300,
height: 60,
child: AnimatedContainer(
duration: const Duration(seconds: 1),
curve: Curves.bounceOut,
alignment: _right ? Alignment.centerRight : Alignment.centerLeft,
onEnd: () => setState(() => _right = !_right),
child: const Icon(Icons.circle, size: 40),
),
);
}
}The first build does not animate, so onEnd is never called and nothing moves. Add initState code that schedules one setState after the first frame to start the loop. A loop built from onEnd also has no way to stop cleanly. If you want repeating motion, explicit animation with repeat is the better tool, and a later chapter covers it.
Exercises
Exercise
A Container has color: Colors.red and decoration: BoxDecoration(borderRadius: BorderRadius.circular(8)). You switch it to AnimatedContainer. What happens, and how do you fix it?
Show answer
It throws an assertion error because a container cannot have both a color and a decoration. Move the color into the decoration: BoxDecoration(color: Colors.red, borderRadius: BorderRadius.circular(8)).
Exercise
A box has width: _open ? 200 : null inside an AnimatedContainer. Tapping to open it makes the box jump instead of growing. Why, and what is one fix?
Show answer
With a null width there is no starting number to tween from, so the widget snaps to 200. Give the closed state an explicit number, such as _open ? 200 : 100.
Exercise
You tap a 400 ms AnimatedContainer at 350 ms into a transition. The target changes back to the original value. Does the animation jump, finish first, or start a new transition? How long does it take?
Show answer
It starts a new transition from the current in-between value to the new target. It does not jump. The new transition runs for the full 400 ms.