Last Updated on 2021-10-12 by Clay
In the process of designing an application, we often need to transform the component to animate it.
A common example is to display an animation like a scroll spreading out when many options are expanded.
Of course, it is possible to directly change the length and width of the component, but it is always better to add a gradual animation.
The article will describe how to use AnimatedContainer to complete the gradual animation of component deformation.
AnimatedContainer is a widget similar to Container, but it will automatically create an animation between old value and the new value when we change the properties of the AnimatedContainer.
How to use AnimatedContainer
We will need to use the following components:
StatefulWidget: Every time you change the component properties on the update pageAnimatedContainer: A component that will automatically generate gradient animationFloatingActionButton: Buttons to control component deformation
In addition, the changed attribute values of AnimatedContainer are generated in random, and the following various attribute values are changed respectively:
heightwidthdecoration-borderRadiusdecoration-colorduration
Let’s take a sample code.
import 'dart:math';
import 'package:flutter/material.dart';
// Main
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: AnimatedContainerPage(),
);
}
}
class AnimatedContainerPage extends StatefulWidget {
@override
_AnimatedContainerPage createState() => _AnimatedContainerPage();
}
class _AnimatedContainerPage extends State<AnimatedContainerPage> {
// Init
int _duration = 1000;
double _width = 100.0;
double _height = 100.0;
Color _color = Colors.red;
BorderRadiusGeometry _borderRadius = BorderRadius.circular(0);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("AnimatedContainer test"),
),
// AnimatedContainer component
body: Center(
child: AnimatedContainer(
width: _width,
height: _height,
decoration: BoxDecoration(
color: _color,
borderRadius: _borderRadius,
),
duration: Duration(milliseconds: _duration),
curve: Curves.fastOutSlowIn,
),
),
// Button
floatingActionButton: FloatingActionButton(
child: Icon(Icons.replay_circle_filled),
backgroundColor: _color,
onPressed: () {
// Rebuild the widget
setState(() {
_duration = 500 + Random().nextInt(500);
_width = Random().nextInt(200).toDouble();
_height = Random().nextInt(200).toDouble();
_color = Color.fromRGBO(
Random().nextInt(256),
Random().nextInt(256),
Random().nextInt(256),
1,
);
_borderRadius = BorderRadius.circular(Random().nextInt(100).toDouble());
});
},
),
)
);
}
}
Output:
References
- https://api.flutter.dev/flutter/widgets/AnimatedContainer-class.html
- https://flutter.dev/docs/cookbook/animation/animated-container
- https://medium.com/flutter-community/flutter-animatedcontainer-widget-ede30bd98931