Getting to know Flutter: Hero animations

Do you want to know how to make beautiful animations where the same image or text is animated alongside push/pop animations? This tutorial is for you.

As you already know in Flutter everything is a widget so guess what you should use to do those animations? A widget of course and in particular the Hero widget. It will take care of moving and stretching the widgets from the position and size of the first screen to the position and size of the second one. It will make the widget “fly” from one screen to the other (yes that’s why it’s called Hero).

Here’s an example of what you can build using the Hero widget:

Hero animations are one of the easiest animation to build in Flutter, you just have to wrap the 2 widgets on the different screens with an Hero widget and give them the same tag.

Here’s a code example:

The Hero Widget has several parameters that you can use if you want to play with the animations.

The flightShuttleBuilder parameter

The flightShuttleBuilder parameters lets you provide another widget during the transition. The code below will show a red container during the transition that animates the opacity but you can provide a different widget of your choice.

The placeholderBuilder parameter

You can provide a Widget as a placeholder using the placeholderBuilder parameter, this will show the widget in the final position of the widget during the transition, for example the following code that returns just a red Container as a placeholder will produce the result that you see in the video. The red container is placed in the space that will be occupied by the image widget, during the transition.

The createRectTween parameter

You could also change the position and size of the widgets during the transition using the createRectTween parameter.

If you want to dig deeper into what’s behind Hero check out the official documentation