Google News
logo
Flutter - Interview Questions
What is a Flutter hero animation and how is it used?
A Flutter hero animation is a special type of animation that animates the transition of a widget from one screen to another. It is commonly used to create smooth and seamless transitions between two screens that contain a common widget.

The basic idea behind a hero animation is that a widget on one screen is "hero" animated to the corresponding widget on another screen. During the animation, the widget is scaled up or down, and its position and size are interpolated to match the widget on the other screen.

To use a hero animation in Flutter, you need to define a hero widget on both screens with the same tag. The tag is a string that uniquely identifies the hero widget across the two screens. When the user navigates from one screen to another, the Flutter framework automatically animates the hero widget using the defined animation.
Here's an example of how to use a hero animation in Flutter:

class FirstScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (_) => SecondScreen()),
          );
        },
        child: Hero(
          tag: 'myHeroTag',
          child: Image.asset('assets/my_image.png'),
        ),
      ),
    );
  }
}

class SecondScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: () {
          Navigator.pop(context);
        },
        child: Center(
          child: Hero(
            tag: 'myHeroTag',
            child: Image.asset('assets/my_image.png'),
          ),
        ),
      ),
    );
  }
}

In this example, the hero widget is an image that is displayed on both the first and second screen. The `GestureDetector` widget is used to detect taps on the widget, and the `Navigator` widget is used to navigate between the two screens. The `Hero` widget is used to define the hero animation, and the tag is set to the same string on both screens. When the user taps on the image, the app navigates to the second screen, and the hero animation is automatically triggered, smoothly transitioning the image from the first to the second screen.

Advertisement