How to use Hero in Flutter

Do you watch movies? Or, do you read novels or stories? In any cinema, or novel, there is only one Hero. Right? In Flutter there is only one Hero animation. When we use the Hero Widget, we have to maintain that.

How do we maintain that?

Well, we will see in a minute.

Before that, let us learn a few facts about the Hero Widget of Animation.

When a Widget flies from one page, or screen to another page, or screen, we call it Hero Animation.

What does that mean?

One Hero Widget flies from the first page to the second page. Subsequently, it can fly from the second page to the third page. And the journey may continue.

However, how will we distinguish between several Hero Widgets.

Each Hero Widget has a parameter called the “tag”. Watch the code snippet below.

child: Hero(
              tag: 'wb',
              child: Container(
...

The above Hero is distinguished by the “tag” parameter.

As a result, we can access to the particular Hero Widget by the “tag” in any page.

Consequently the Hero Widget implements a special type of animations. It is known as the “shared-element-transitions”, or “shared-element-animations”.

Imagine a Flutter screen where we use different type of locations. We can just start with one Image Widget and wrap it with the Hero Widget. Therefore, it represents one location.

import 'package:flutter/material.dart';

import 'west_bengal.dart';

class AllLocations extends StatelessWidget {
  const AllLocations({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Wrap(
        spacing: 18.0, // gap between adjacent chips
        runSpacing: 14.0, // gap between lines
        children: [
          Container(
            margin: const EdgeInsets.all(20),
            padding: const EdgeInsets.all(20),
            child: const Text(
              'Choose Locations',
              style: TextStyle(
                fontFamily: 'Allison',
                fontSize: 60,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          const SizedBox(
            height: 10,
          ),
          GestureDetector(
            onTap: () => Navigator.push(context,
                MaterialPageRoute(builder: (context) => const WestBengal())),
            child: Hero(
              tag: 'wb',
              child: Container(
                padding: const EdgeInsets.all(10),
                width: 100,
                height: 100,
                child: Image.network(
                    'https://cdn.pixabay.com/photo/2021/11/13/23/06/tree-6792528_960_720.jpg'),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

In the above code, there is one Hero Widget. Moreover, the Hero is distinguished by a special parameter “tag”.

To understand the concept let us take a look at the screenshot.

Flutter Hero animation first page
Flutter Hero animation first page

Now, we can click the Image Widget and the Hero with the “tag” will fly to the second page.

Hero in Flutter second page
Hero in Flutter second page

If we take a look at the code of second page now, we will find the same Hero “tag”.

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

class WestBengal extends StatelessWidget {
  const WestBengal({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('West Bengal'),
      ),
      body: Center(
        child: Hero(
            tag: 'wb',
            child: ListView(
              children: [
                Container(
                  padding: const EdgeInsets.all(10),
                  width: 350,
                  height: 350,
                  child: Image.network(
                      'https://cdn.pixabay.com/photo/2021/11/13/23/06/tree-6792528_960_720.jpg'),
                ),
                Container(
                  padding: const EdgeInsets.all(5),
                  child: RichText(
                    text: TextSpan(
                      text: 'West Bengal ...',
                      style: const TextStyle(
                        fontSize: 30.0,
                        color: Colors.blue,
                      ),
                      children: [
                        TextSpan(
                          text: ' A land where I was born and fell in love ...'
                              'with learning Flutter. Why? Because there are '
                              ' so many trees and butterflies around us ...',
                          style: const TextStyle(
                            fontSize: 20.0,
                            color: Colors.red,
                          ),
                          recognizer: TapGestureRecognizer()
                            ..onTap = () {
                              Navigator.pop(context);
                            },
                        ),
                        TextSpan(
                          text: ' Read More ...',
                          style: const TextStyle(
                            fontSize: 15.0,
                            color: Colors.green,
                          ),
                          recognizer: TapGestureRecognizer()
                            ..onTap = () {
                              Navigator.pop(context);
                            },
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            )),
      ),
    );
  }
}

I hope you get the idea. Similarly, we can use several Hero Widgets. But we need to distinguish each Hero Widget with the different “tag”.

For full code snippet please visit the respective GitHub repository.

How to make a hero animation in flutter?

The key concept that works behind the scene is controlled by the Hero Controller.

Certainly, we can make the Hero Widget fly from one screen, or page to any screen, or page. However, when the navigation happens, each route is identified by the Hero Controller.

As a result, the “parent” Hero Widget marks its “child” Hero Widget as a candidate for the Hero Animations. After that, the Hero Widget that acts as the “child”, may act as the “parent” again.

However, the Hero Widget should always be distinguished by the “tag”.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

Courses at Educative

GitHub repository

Technical blog

Twitter

Comments

3 responses to “How to use Hero in Flutter”

  1. […] a result, the color of the Text Widget changes from the dark Red to […]

  2. […] understand the Tween Animation in Flutter we need to realize one key […]

  3. […] learn tween animation. Because we have a separate section for that, and you may check how the Tween Animation in Flutter takes […]

Leave a Reply