Fade in your UIs in Flutter
⚠ This article covers a previous version of Simple Animation. The basics stay the same but class names have changed.
Earlier this week I introduced the Flutter package simple_animations. Today I want to follow up with a practice example, you can use in your apps.
In Flutter it’s very easy to create beautiful UIs. And animations will add the little “extra” to them. So, let’s augment our static looking UI with some cool fade-in animations:
Let’s begin. Given we have our app like this:
… that will look like this:
To meet the needs of Flutter’s composition approach we will design a Widget FadeIn that wraps each UI widget and applies a fade-in animation to it.
It will take the following parameters:
- delay: an abstract unit to specify the order in which we fade-in our elements. We’ll use on a Double value. (Larger values = appear later)
- child: the Widget to animate.
Let’s take a look of it’s code and discuss how we realized it:
From line 2 till 6 we just apply our widget variables. Then we have the Widget’s builder function. It utilizes two aspects of simple_animation.
First we design a MultiTrackTween. It’s an Animatable that tweens multiple properties at once. We want to animate in parallel
- the opacity from 0.0 (invisible) to 1.0 (fully visible) and
- a translation on the x-axis from 130.0 (looking a little displaced) to 0.0 (looking unmodified).
Then we want to animate this tween using ControlledAnimation, a widget that simplifies tween-based animation.
The following line solves our delay-requirements by translating our abstract Double value into time. You can freely play around with this value to get results you like:
delay: Duration(milliseconds: (300 * delay).round())
The animation execution will wait until the specified Duration is passed.
The rest is just using the builderWithChild function to efficiently build the animated scene using a pre-build child. In the builder function we use Flutter’s build-in Translate and Opacity widgets, that we are feeding with the tweened values.
builderWithChild: (context, child, animation) => Opacity(
offset: Offset(animation["translateX"], 0),
Now our FadeIn widget is ready to be used. We just need to wrap our UI elements with a desired delay-value like this:
And here is my interpretation of a smoothly faded-in UI…
… that will look like this:
If you are now interested in creating “your own interpretation” of this fade-in animation, the whole demo is accessible in the Simple Animations Example App. Just check it out and play around.
If you want to use the simple_animations in your app, visit the Pub Dart page. You can also find a complete documentation to discover all features.
If you liked this kind of tutorials leave some claps. Then I know to write you guys some more. You can find the previous one here.
— Felix —