Introduction
In this blog, we’re going to implement some examples of basic animations in Flutter. In the previous article, I explained some basic concepts of animation which needs to be understand before diving into animation. So, if you want to understand those concepts of animation, head over to that article.
First, we’ll see very simple rotation animation.
Create home_screen.dart file and copy the following code inside it
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State with TickerProviderStateMixin {
Animation _arrowAnimation;
AnimationController _arrowAnimationController;
@override
void initState() {
super.initState();
_arrowAnimationController =
AnimationController(vsync: this, duration: Duration(milliseconds: 300));
_arrowAnimation =
Tween(begin: 0.0, end: pi).animate(_arrowAnimationController);
}
@override
Widget build(BuildContext context) {
}
}
In initState() method, _arrowAnimationController is initialised with duration of animation equal to 300 milliseconds.
After that, _arrowAnimation is initialise with begin value of 0.0 and end value of pi (value = 180) so that, it will rotate by 180 degrees.
Now, comes the layout part of the screen, paste the following code inside build() method
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Example Animations'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
firstChild(),
],
),
);
}
Now, let’s create firstChild() Widget, where the actual widget will be present that contains a widget that needs to be animate and another widget that starts the animation.
Widget firstChild() {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
AnimatedBuilder(
animation: _arrowAnimationController,
builder: (context, child) => Transform.rotate(
angle: _arrowAnimation.value,
child: Icon(
Icons.expand_more,
size: 50.0,
color: Colors.black,
),
),
),
OutlineButton(
color: Colors.white,
textColor: Colors.black,
padding: const EdgeInsets.all(12.0),
child: Text('Start Icon Animation'),
onPressed: () {
_arrowAnimationController.isCompleted
? _arrowAnimationController.reverse()
: _arrowAnimationController.forward();
},
splashColor: Colors.red,
)
],
);
}
In the given code, first child of Row is Icon that needs to be animated and it is wrapped with AnimatedBuilder widget.
AnimatedBuilder widget is a widget that is useful for building animations. It is more effective and efficient way of animating any Widget than calling setState() method on each change in value of animation.