This tutorial aims to introduce the Animation Controller in Flutter. We will learn how to use this powerful tool to create and manage animations in our Flutter applications.
By the end of this tutorial, you will be able to:
Before starting this tutorial, you should have:
In Flutter, the Animation Controller is a type of Animation
First, you need to create an instance of the AnimationController. This is usually done in the initState() method of your StatefulWidget.
AnimationController controller;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
);
}
In the above code, vsync stands for "visual sync". It is an optional property that prevents off-screen animations from consuming unnecessary resources.
AnimationController controller;
Animation<double> animation;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
);
animation = Tween<double>(begin: 0, end: 300).animate(controller)
..addListener(() {
setState(() {
// This causes the widget to rebuild every time the animation changes value.
});
});
controller.forward();
}
In this example, we use the Tween class to define a range for the animation. The animate() method returns an Animation object, which we then add a listener to. This listener calls setState() every time the animation value changes, causing the widget to rebuild.
controller.reverse();
The reverse() method will play the animation in reverse from its current position.
In this tutorial, we've learned about the Animation Controller in Flutter and how to use it to create custom animations. We've explored how to initiate, reverse, and manage animations, and we've seen how changes in the animation trigger widget rebuilding.
Create a simple animation where an object moves from the left side of the screen to the right.
Enhance the previous exercise by making the object move back to the left side of the screen once it reaches the right.
AnimationController controller;
Animation<double> animation;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
);
animation = Tween<double>(begin: 0, end: 300).animate(controller)
..addListener(() {
setState(() {
});
});
controller.forward();
}
AnimationController controller;
Animation<double> animation;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
);
animation = Tween<double>(begin: 0, end: 300).animate(controller)
..addListener(() {
setState(() {
});
});
controller.forward().then((_) {
controller.reverse();
});
}
In the second exercise, we use the then() method to wait for the forward animation to finish before starting the reverse animation.