Saturday, July 18, 2020

Build a simple Flutter loading animation

In this example the Flutter animation controller is used to count between zero and three. The IntTween class is bound to the animated controller so the count up or down based on the the animation direction. Then the animation count is used to display the periods in the loading display. 



Configure the Animation Counter
The animation controller is easy to configure. 

1. Add the mixin SingleTickerProviderStateMixin

class _LoadingState extends State<Loading%gt; 
	with SingleTickerProviderStateMixin { //... }
  
2. Initialize the animation controller and counter
@override
void initState() {
  super.initState();
  _controller =
      AnimationController(vsync: this, duration: Duration(seconds: 1));
  _animation = IntTween(begin: 0, end: totalPeriodCount).animate(_controller)
    ..addStatusListener((state) {
      if (state == AnimationStatus.completed) {
        // NOTE: Change the animation counter direction
        _controller.reverse();
      } else if (state == AnimationStatus.dismissed) {
        // NOTE: Change the animation counter direction
        _controller.forward();
      }
    })
    ..addListener(() {
      // NOTE: Update the view
      setState(() {});
    });
  _controller.forward();
}
  
Controlling the Animation Notes:
  • Use _controller.reverse() to reverse the animation counter. 
  • Use _controller.forward() to advance the animation counter. 
  • And be sure to update the views state using setState((){}) so the view is updated.

3. Use the animation counter. Use _animation.value to reference the value for displays frame. 

int visiblePeriodCount = totalPeriodCount - _animation.value;
  
4. Tear down the animation controller
@override
void dispose() {
  _controller.dispose();
  super.dispose();
}

Try it out
Putting it all together, try out this animation example in the DartPad:


Overall 
This example shows how easy it is to use the animations in Flutter. The simplicity the Flutter animation controller makes it easy to build beautiful application animations that bring a lot of joy to application usage. 

I hope you enjoyed this small tutorial. I'd love to hear what you used the animation controller. Please share your tips and tricks below. 

No comments:

Trying out the Dart Analysis Server

I wanted to see how the Dart Analysis Server was put together and worked. I started looking to see how I could wire it up and try out the co...