Sub topic 4
Your First Implicit Animation: AnimatedContainer
Prerequisites and the basic idea
This chapter assumes you know Dart classes, Flutter widgets, StatefulWidget, setState, and basic layout widgets.
An implicit animation is an animation where Flutter manages the animation controller for you. You provide a new property value, and Flutter smoothly changes the old value into the new value.
AnimatedContainer is a Container that animates changes to properties such as:
widthandheightcolorpaddingandmarginalignmentdecorationborderRadius
The widget must rebuild with different values. Usually, a user action calls setState, which changes a field. Flutter then compares the old and new properties and animates between them.
A complete example
This example switches between a small orange box and a large teal box.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: GrowingBoxPage()));
}
class GrowingBoxPage extends StatefulWidget {
const GrowingBoxPage({super.key});
@override
State<GrowingBoxPage> createState() => _GrowingBoxPageState();
}
class _GrowingBoxPageState extends State<GrowingBoxPage> {
bool _big = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('AnimatedContainer')),
body: Center(
child: GestureDetector(
onTap: () {
setState(() {
_big = !_big;
});
},
child: AnimatedContainer(
duration: const Duration(milliseconds: 400),
curve: Curves.easeInOut,
width: _big ? 200 : 100,
height: _big ? 200 : 100,
decoration: BoxDecoration(
color: _big ? Colors.teal : Colors.orange,
borderRadius: BorderRadius.circular(_big ? 24 : 4),
),
),
),
),
);
}
}duration sets how long the transition takes. curve controls its timing. Curves.easeInOut starts slowly, moves faster, and slows down at the end.
The ternary expressions choose values based on _big. On every tap, setState changes _big, causing build to run. AnimatedContainer sees the new values and animates supported differences automatically.
Common errors and limits
A frequent mistake is changing a field without calling setState. The field changes, but Flutter does not rebuild the widget, so no animation starts.
Another mistake is expecting every change to interpolate. Numbers, colors, and many decorations can change smoothly. A completely different child widget is replaced rather than gradually transformed. Use a more specialized animation widget when the effect needs precise control.
If the animation looks too fast, increase duration. If it feels unnatural, try another curve. Keep the transition short enough that the interface still feels responsive.
> callout note > AnimatedContainer animates between values supplied by successive builds. It does not create an animation from a single fixed value. >
Exercise
What must happen before AnimatedContainer can animate from one width to another?
Show answer
A rebuild must provide a different width, usually after setState changes state.