AnimatedContainer: Simple UI Animations Without Controllers
AnimatedContainer is a 'fire-and-forget' animation widget. It automatically animates its own properties like size and color when they change. Use it for simple UI state changes, like a button that grows when tapped. It only animates itself, not its child.
WHY IT EXISTS Many UI animations involve simple changes to a widget's size, color, or position. Managing an AnimationController for these basic cases adds unnecessary boilerplate code. AnimatedContainer was created to provide a simple, declarative way to achieve these common animations implicitly.
THE MENTAL MODEL Think of AnimatedContainer as a regular Container with a built-in animator. When you change its properties (like width or color) inside a StatefulWidget's setState, it doesn't just snap to the new values. Instead, it smoothly transitions from the old state to the new state over a specified duration.
HOW IT WORKS AnimatedContainer is an ImplicitlyAnimatedWidget. When Flutter rebuilds it with new property values, the widget compares the new values to the old ones. For any properties that have changed (and are not null), it automatically creates and runs an animation using the provided duration and curve to interpolate between the start and end values. You don't manage any controllers; you just declare the end state.
WHEN TO USE IT Use it for basic, state-driven animations of a container's appearance. This is perfect for making a button grow or change color on tap, smoothly adjusting layout padding, or animating a background based on a selection. It's the go-to for simple, implicit transitions where you don't need fine-grained control.
WHEN NOT TO USE IT For complex sequences or when you need to pause, reverse, or link multiple animations, use an explicit AnimationController. Crucially, AnimatedContainer does not animate its child widget. To animate the transition between different children, use a widget like AnimatedSwitcher or AnimatedCrossFade.
ONE CANONICAL EXAMPLE A common use is a box that changes size and color when tapped. You would have a StatefulWidget with a _tapped boolean. The AnimatedContainer's width, height, and color properties would be determined by this boolean. In an onTap callback, you call setState to toggle _tapped, and the AnimatedContainer automatically animates the transition to the new dimensions and color over its specified duration.
Read the original → api.flutter.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.