DEV Community

Cover image for Flutter Hero Animation
Reme Le Hane
Reme Le Hane

Posted on • Edited on • Originally published at remejuan.substack.com

Flutter Hero Animation

A useful skill in Flutter is mastering Hero Animations, which allow you to create smooth and engaging transitions between screens by animating a widget (such as an image or text) across route changes.

Example: Hero Animation

This code demonstrates a simple Hero animation where an image transitions smoothly between two screens:

  1. Main Screen with a small image:
  2. Detail Screen where the image appears larger.

Step 1: Create Main Screen

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MainScreen(),
    );
  }
}

class MainScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Main Screen")),
      body: Center(
        child: GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (_) => DetailScreen()),
            );
          },
          child: Hero(
            tag: 'imageHero',
            child: Image.network(
              'https://via.placeholder.com/150',
              width: 150,
              height: 150,
            ),
          ),
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Create Detail Screen

class DetailScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Detail Screen")),
      body: Center(
        child: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: Hero(
            tag: 'imageHero',
            child: Image.network(
              'https://via.placeholder.com/150',
              width: 300,
              height: 300,
            ),
          ),
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

How it Works:

  • Hero Widget: Wrap the widget you want to animate with a Hero widget and assign it a unique tag.
  • Smooth Transition: When navigating between screens, Flutter automatically animates the Hero widget between the two routes.

This is a great way to improve the UX of your app by providing visually appealing transitions with minimal effort.

Top comments (0)