Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

flutter
hero
communitycreator

How to use the Hero class in Flutter

Hammad Qayyum

Flutter is an open-source framework by Google for building beautiful, natively compiled, multi-platform applications from a single codebase.

The Hero class in Flutter is a widget that marks its child for the hero animations. Hero transitions are very common in mobile application development. They are mostly used as indicators to let users know they have changed the screens while keeping the focus of the interaction towards the front and center. Flutter’s Hero widget automatically creates a hero transition between two navigator routes.

When the routes of a page are pushed or popped, the entire screen’s content is replaced by the other screen. If this change of content is done by some animations, it becomes helpful for orienting the user for the feature to physically move from one place to another. Such an animation is called hero animation.

Usage

To use this class in our flutter application, we need to wrap the widgets of both screens inside the hero’s widget. The Hero class in both pages is provided a tag by the developer. This tag should be the same for both screens involved in the animations because it specifies the screens in an animation.

Code

Let’s create a new Flutter application named hero_flutter. The code of both screens is given below.

The main.dart file looks like this:

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Heros Flutter'),
      ),
      body: GestureDetector(
        onTap: (){
          Navigator.push(context, MaterialPageRoute(builder: (context)=>NewPage()));
        },
        child: Hero(
          tag: 'dash',
          child: Image.network("https://images.unsplash.com/photo-1638579837195-3fb3b3287506?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0fHx8ZW58MHx8fHw%3D&auto=format&fit=crop&w=500&q=60")
          ),
      ),
    );
  }

Now, we add the code of the new screen in the newpage.dart file given below:

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('New Screen'),),
      body: Center(
        child: Hero(
          tag: 'dash',
          child: Image.network("https://images.unsplash.com/photo-1638579837195-3fb3b3287506?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0fHx8ZW58MHx8fHw%3D&auto=format&fit=crop&w=500&q=60", )),
      ),
    );
  }

Code explanation

The code above contains the hero widget with different parameters such as tag and its child. tag provides the widget with a unique id required to be the same in both the hero widgets. child then contains the new widget that is displayed inside the hero widget.

RELATED TAGS

flutter
hero
communitycreator
RELATED COURSES

View all Courses

Keep Exploring