import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Hero Animation Demo',
home: const ImageListScreen(),
);
}
}
class ImageListScreen extends StatelessWidget {
const ImageListScreen({super.key});
final List<Map<String, String>> images = const [
{'tag': 'image1', 'url': 'https://picsum.photos/id/1011/200/200'},
{'tag': 'image2', 'url': 'https://picsum.photos/id/1012/200/200'},
{'tag': 'image3', 'url': 'https://picsum.photos/id/1013/200/200'},
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Images')),
body: ListView(
padding: const EdgeInsets.all(8),
children: images.map((image) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => ImageDetailScreen(
imageTag: image['tag']!,
imageUrl: image['url']!,
),
),
);
},
child: Hero(
tag: image['tag']!,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Image.network(image['url']!, width: 200, height: 200, fit: BoxFit.cover),
),
),
);
}).toList(),
),
);
}
}
class ImageDetailScreen extends StatelessWidget {
final String imageTag;
final String imageUrl;
const ImageDetailScreen({super.key, required this.imageTag, required this.imageUrl});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Image Detail')),
body: Center(
child: Hero(
tag: imageTag,
child: Image.network(imageUrl, width: 300, height: 300, fit: BoxFit.cover),
),
),
);
}
}
We created a list of images each wrapped in a Hero widget with a unique tag. When the user taps an image, the app navigates to a detail screen passing the tag and URL. The detail screen also uses a Hero widget with the same tag to create a smooth transition animation between the small image and the large image. This demonstrates the hero animation concept in Flutter simply and clearly.