Understanding components for a basic animation in Flutter

An animation is nothing but some values which change over time. For example, when we click on the button we want to animate the score widget rising from bottom, and when we leave the button it should rise even more and then hide.

If you look only at the score widget, we need to change the values of position and opacity of widget over some time.

Score Widget

Let’s say we want out score widget to take 150 ms to reveal itself from bottom. Think of this on a timeline as below

This is a simple 2D graph. The position would change with time.

Notice that the diagonal line is straight. This can even be a curved if you like.

You can make the position increase slowly with time and then get faster and faster. Or you could have it come in a super high speed and then slow down at the end.

This is where we get to introduce out first component : Animation Controller.

Animation Controller Construction

Here, we have created a simple controller for the animation. We have specified that we want to run the animation for a duration of 150ms. But, what is that vsync?

Mobile devices refresh their screen after every few milliseconds. That is how we perceive set of images as a continuous flow or a movie.

The rate at which the screen is refreshed can vary from device to device. Let’s say the mobile refreshes its screen 60 times a second (60 Frames per Second). That would be after every 16.67 ms, we feed a new image to our brain. Sometimes, things can get misaligned (we send out a different image while the screen was refreshing) and we get to see screen tearing. VSync takes care of that.

Let us add a listener to the controller and run the animation.

The controller generated numbers from 0.0 to 1.0 in 150 ms. Notice that the values generated are almost linear. 0.2, 0.3, 0.4 … How do we change this behavior? This would be done by out second component : Curved Animation

We create a Curved animation by setting the parent as our controller and providing the curve we want to follow. There are a range of choices of curves we can use at flutter curves documentation page. The controller provides value from 0.0 to 1.0 to the curved animation widget over a period of 150 ms. The curved animation widget interpolates those values as per the curve we have set.

Still, we are getting value from 0.0 to 1.0. But we want values from 0.0 to 100.0 for our score widget. We could simply multiply by 100 to get the result. Or we can use the third component : The Tween Class

The tween class generated values from begin to end. We have used our earlier scoreInAnimationController which uses a linear curve. Instead we could have used our bounce curve to get different value. Advantages of Tween does not end here. You can tween other things too. You can directly tween color, offset, position and other widget properties using classes which further extends the base tween class.