Animating Widgets

Let’s start by defining our various animations. As we discussed earlier, there are three key steps this animation: translation, fade/opacity and timing.

The above snippet define animations for translation and opacity of our various widgets. Notice the difference in types, our translation Animation defines an Offset while our opacity and controller expects double .

Since we are using the animation provided by the route, we need to override didChangeDependencies so that the animation for the given ModalRoute may be accessed via the context . If you are wondering why we are not using initState() , it is because context is not available in initState() .

If the controller variable we defined is null, the value from ModalRoute is used. Next we can start defining our Tweens. Let's start by defining the translation tween for the header image:

So what is going on here? We are using a Tween to specify a start and end value. We are then using a CurvedAnimation and an Interval to animate our Tween . The values passed to Interval represent the start and end percentage of the animation. Here, we are starting at 0.0s and ending at 67% or approximately 4 seconds into the total animation.

Now, we can define the remaining Tween :

With our Tweens now defined, the final step is to wire them to our static widgets. Let’s navigate to the build method of _CoolAnimatedAppState and wrap our Column in an AnimatedBuilder . Animated Builder requires an animation so for this we are going to pass it our controller variable. Next, we need to wrap our widgets in a widget which allows it to animate its position. There are many widgets we can use for this but to keep things simple, we are going to use FractionalTranslation . Fractional Translation moves it's child fractionally in relation to its parent. For example, if the parent defines a height of 200 pixel and you apply a 0.25 translation, then the child will be moved to 50 pixel or a quarter of the height of the parent.

The snippet above shows our widget tree with FractionalTranslation added. Note the value being passed for translation is the value of the corresponding variable (Tween). I refactored the three main components into their own StatelessWidgets to make the code a bit shorter and easier to read.

Last but not least is the fade animation. For this, we are again going to keep this relatively simple and use a FadeTransition . Let's update our code so that the child of our FractionalTranslation is a FadeTransition . Again we pass the corresponding Tween for the opacity value of our FadeTransition .

Now if we hot restart our app, we should hopefully see our animation!