Flutter
AnimatedContainer
Animate property changes with AnimatedContainer.
What is AnimatedContainer?
AnimatedContainer is the animated version of Container. When you change properties like width, height, or color, it animates the change smoothly over the duration. You provide new values and Flutter handles the rest.
class Ornek extends StatelessWidget {
const Ornek({super.key});
@override
Widget build(BuildContext context) {
return AnimatedContainer(
duration: const Duration(seconds: 1),
width: 50,
color: Colors.blue,
);
}
}
This widget automatically plays a transition animation when the width and color values change.
The duration parameter
The duration parameter takes a Duration object and sets the total animation time. This parameter is mandatory; without it, AnimatedContainer would not know how fast to transition. Duration(seconds: 1) gives a one-second transition, while Duration(milliseconds: 300) gives 300 milliseconds.
AnimatedContainer(
duration: const Duration(milliseconds: 300),
width: 100,
)
Exercise Define an AnimatedContainer
Define a StatelessWidget named Ornek. Its build method should return an AnimatedContainer with duration set to Duration(seconds: 1) and width set to 50. Print 'hazir' in main.
Show example solution
import 'package:flutter/material.dart';
class Ornek extends StatelessWidget {
const Ornek({super.key});
@override
Widget build(BuildContext context) {
return AnimatedContainer(
duration: const Duration(seconds: 1),
width: 50,
);
}
}
void main() {
print('hazir');
}
Test yourself
-
Which parameter of AnimatedContainer determines the animation duration?
Show answer
duration — The duration parameter determines how long the animation takes. width and color are animated properties, and child is the inner widget; none of them control duration.
-
The duration parameter
AnimatedContainer(
____: const Duration(seconds: 1),
width: 50,
)
Show answer
AnimatedContainer(
duration: const Duration(seconds: 1),
width: 50,
)
-
AnimatedContainer parts
- AnimatedContainer
- Animated container
- duration
- Animation duration
- width
- Width value
- color
- Color value
Next lesson: Tween