Featured Image
Software Development

Options to Animate in Flutter

Animations in Flutter is really easy and awesome.

Ohh! you know this? That’s great then I am sure that while searching for animations in Flutter you must have seen various ways to do it. In this article, I am going to show you some of the options to animate in Flutter.

Let’s first see what actually we are going to animate.

 
Flutter animation of flying Iron Man character

Image by http://vecteezy.com

We will be going to fly our Iron man. We will just animate him from bottom to top but using different ways. Let’s see what are they.

Option 1: Pure Animation code

Use this option only if you don’t want to use any implicit(readymade) animated widgets. Don’t worry if you don’t know what is an implicit animated widget. We will cover the rest of options with implicit animated widgets only. Give a quick look at the code so that it can become easy to catch what’s going on.

animationController =
    AnimationController(vsync: this, duration: Duration(seconds: 3));
animation = Tween<double>(begin: 0, end: -300).animate(animationController)
  ..addListener(() {
    setState(() {});
  });

animationController and animation are used together to control the animation, We are giving time to finish animation as duration to animationControllerandbegin and end position to animation using Tween. Twin object is used to create intermediate values from begin to end value.

Align(
  alignment: AlignmentDirectional(0,0.7),
  child: Transform.translate(
    offset: Offset(0, animation.value),
    child: Container(
      height: 250,
      width: 170,
      decoration: BoxDecoration(
          image: DecorationImage(
        image: AssetImage('assets/images/ironman.png'),
      )),
    ),
  ),
),

This is the widget which aligns the iron man at bottom and moves to the top when the animation starts. One important line to notice here is offset: Offset(0, animation.value), this property of Transform.translate will move to a position that animation generates. In our case, it would be from 0 to -300 in an upward direction.

onPressed: () {
  animationController.forward();
},
Credit: https://giphy.com

This code actually triggers the animation and congratulations! you have just learned hard option first.

Also read: Exploring Sensitive Data Handling, API Calls, and JSON Serialization in Your Flutter Heroes App

Option 2: AnimatedBuilder

AnimatedBuilder is a specialized widget that listens to the values generated on the Animation object that is given to its animation property.

How it is different from option1?

.animate(animationController)
  ..addListener(() {
    setState(() {});
  });

No major difference as such but you can get rid of the above code if you don’t want to listen to animation state. Also, you have to wrap Transform.translate inside AnimatedBuilder so that it can listen to animation values. Check the full code here.

Option 3: SlideTransition

Use this when you want to change the position of a widget relative to its current position.

Align(
  alignment: AlignmentDirectional(0.0, 0.7),
  child: SlideTransition(
      position: animation,
      child: Container(
        height: 250,
        width: 150,
        decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/ironman.png'),
            )),
      )
  ),
),

You don’t need AnimatedBuilder and Transform.translate because SlideTransition does the job of two. Look at this position: animation property. It listens for animation values as well as change the position of the widget.

Sine position property expecting animation of object offset, we needed to change from this.

animation = Tween<double>(begin: 0, end: -350).animate(animationController);

To this. The tween of Offset.

animation = Tween<Offset>(begin: Offset(0, 0), end: Offset(0, -1.2)).animate(animationController);

Try to play with the below code.

Also read: Flutter Text Reader Animation: Bringing Text to Life

Option 4: AnimatedPositioned

This is one of the implicit animated widgets. You don’t need animationController, animation, and Tween. So where we will define Duration? Good question. Check this out.

AnimatedPositioned(
  duration: Duration(seconds: 3),
  bottom: _ironManAlignment,
  left: 90,
  child: Container(
    height: 250,
    width: 150,
    child: Image.asset('assets/images/ironman.png'),
  ),
),

Here it is → duration: Duration(seconds: 3) and the bottom property has given this

double _ironManAlignment = 50;

Now whenever we change this using

setState(() {
  _ironManAlignment = 320;
});

The animation will be performed automatically moving iron man from bottom position 50 to 320. Ya, you get it for free. The code snippet below.

Option 5: AnimatedContainer

My favorite option. This is also one of the implicit animated widgets. You know now what it is. The main difference from Option4 is that this widget is able to perform automatic transition for all property that one container possesses. Meaning just using this widget you can move iron man from bottom to top as well as you can increase the size of him and what not.

AlignmentDirectional _ironManAlignment = AlignmentDirectional(0.0, 0.7);
AnimatedContainer(
  duration: Duration(seconds: 3),
  alignment: _ironManAlignment,
  child: Container(
    height: 250,
    width: 150,
    child: Image.asset('assets/images/ironman.png'),
  ),
),

Below code will trigger the automatic transition.

setState(() {
  _ironManAlignment = AlignmentDirectional(0.0,-0.7);
});


Done!

There are many things can be done with any of the above options, for example, you can define a Curve like easeIn and easeOut to have real-life momentum to iron man.

All of the above methods will produce the same result. Choose the best fit for your case.

Note: These are not all options but you may find even more while exploring Flutter a little more.

Small Challenge: So you learned good things today. Now it’s time to polish it. I want you to move iron man up and then again at the bottom. If you achieve this, please tweet it. Also, mention me so that I can RT.

Clone it. Play with it:

Here is a demo showcasing various ways to animate in Flutter.
 

Also read: Crafting a Flutter Onboarding Page Indicator in Just 3 Minutes.

author
Pinkesh Darji
I love to solve problems using technology that improves user’s life on a major scale. Over the last several years, I have been developing and leading various mobile apps in different areas. More than just programming, I love to write technical articles. I have written many high-quality technical articles. I have worked with various startups to build their dream app. I have been involved in product development since my early days and know insights into it. I have provided my valuable input while taking some crucial decisions of the app by brainstorming with a design, QA team. Over the last 3 years, I have been developing mobile apps and libraries using Google’s Flutter framework. I mentor junior Flutter developers and review their code. You will also find me talking on various Flutter topics in local meetups.