Animations can add a touch of magic to an app. They have the ability to make an app feel more polished, fluid and engaging. In Flutter, various animation options are available, such as Hero Animation, Tween Animation, and AnimatedBuilder. In this tutorial, we will explore the AnimatedContainer widget, which provides a straightforward way to animate properties of a widget.
AnimatedContainer is a Flutter widget that animates changes to its properties, such as height, width, color and padding. It is an ideal choice if you want to add subtle animations to your app without needing to create a separate animation object.
The AnimatedContainer widget can be used by calling setState() method within Stateful Widget to change its properties. Here is an example:
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State {
bool _expanded = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My App'),
),
body: Center(
child: GestureDetector(
onTap: () {
setState(() {
_expanded = !_expanded;
});
},
child: AnimatedContainer(
duration: const Duration(milliseconds: 500),
curve: Curves.easeInOut,
height: _expanded ? 200 : 100,
color: _expanded ? Colors.red : Colors.blue,
child: Center(
child: Text(
'Tap to expand or collapse',
style: TextStyle(color: Colors.white),
),
),
),
),
),
);
}
}
When the user taps on the widget, a setState() method is invoked to change the value of the _expanded variable. The AnimatedContainer widget then animates the height and color of the widget based on the current value of _expanded variable.
AnimatedContainer Widget has several properties that can be animated:
The AnimatedContainer widget provides an easy and convenient way to animate container properties, such as height, width, padding and color. By using this widget, you can add subtle animations to your app that make it feel more polished and engaging.