It's a very common UX pattern that we are experiencing everyday:
Click an image in gallery, after a smooth transition, show the image in fullscreen mode and then you can zoom to view the details.
But in Flutter, I found it's hard to implement such animation smoothly, sure with Hero widget I can finish the basic code in a minute, but here is the problem: In the gallery, the image is placed in a small square with its fit mode BoxFit.cover, in zoom mode page, its fit mode should be BoxFit.contain. When hero animation starts of ends, the fit mode changed to target abruptly.
// main.dart
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart' show timeDilation;
const String url =
'https://images.unsplash.com/photo-1635335333546-41f848cea96c';
void main() {
runApp(
const MaterialApp(
home: GalleryWidget(),
),
);
}
class GalleryWidget extends StatelessWidget {
const GalleryWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
timeDilation = 10.0;
return Scaffold(
appBar: AppBar(
title: const Text('Gallery'),
),
body: Material(
child: InkWell(
child: Hero(
tag: url,
child: Image.network(
url,
width: 100.0,
height: 100.0,
fit: BoxFit.cover,
),
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const PhotoViewerWidget(url: url),
fullscreenDialog: true,
),
);
},
),
),
);
}
}
class PhotoViewerWidget extends StatelessWidget {
final String url;
const PhotoViewerWidget({Key? key, required this.url}) : super(key: key);
@override
Widget build(BuildContext context) {
return Material(
color: Colors.black87,
child: InkWell(
child: Hero(
tag: url,
child: Image.network(url),
),
onTap: () => Navigator.of(context).pop(),
),
);
}
}