When navigating between screens in a app, it’s helpful to use some visual cues to assist a user in knowing the context of where they came from and where they’re going to. A hero animation is a common technique for implementing such a visual cue.
You can use a hero animation when the screen you’re navigating to has a large image that you can identify as the Hero image and when the screen you’re navigating from has another version of that image, often as a thumbnail in a list of items. That would be the case when you’re going from a list screen to a detail screen, as you’re doing in the RWCourses app.
Setting up a basic hero animation in Flutter is very straightforward. You just wrap the image on both the source and destination screens in a Hero widget, and then give both hero widgets the same tag. Flutter will do the rest for you, animating the image as the user navigates between the screens, both forward and back.
In this episode, you’ll create a basic hero animation. To dive deeper into more Hero animation techniques, check out our course “Flutter Hero Animations”.
To get started, open your project in progress or download the starter episode for this episode. We’re going to add a hero animation to the course thumbnail. Open up courses_page.dart. You can find it in the courses subfolder inside of the ui folder.
Select the ClipRRect widget and right click on it. Select refactor and choose a widget. Change it a Hero widget.
trailing: Hero(
child: ClipRRect(
borderRadius: BorderRadius.circular(8.0),
child: Image.network(
course.artworkUrl,
),
We’re getting an error because we haven’t added a tag to it. Add a tag to the Hero that uses the courseId to create a unique value.
tag: 'cardArtwork-${course.courseId}',
Then set the transitionOnUserGestures value on the hero to true. This makes the animation occur if the transition between screens occurs due to a user gesture, such as a back swipe on iOS, instead of a call to the Navigator.
transitionOnUserGestures: true,
Now open the course_detail_page.dart. In the _buildBanner method, wrap ImageContainer with a similar Hero widget
return Hero(
tag: 'cardArtwork-${course.courseId}',
transitionOnUserGestures: true,
child: ImageContainer(
height: 200,
url: course.artworkUrl,
),
We used the same tag value from the course ID for the hero widget on the course detail screen. When using Hero Animations, it is necessary that we use the same tag. This is how flutter knows the old and new positions of widgets where the image needs to be transitioned during animation. Now build and run or hot reload. Tap on a course listing and look at that, we get a nice hero transition.