主要是利用Flutter中的Hero
Widget来实现夸界面的组件移动动画效果(不背单词App点击头像的动画、查看图片的动画)。
效果如下:
Flutter中使用Hero组件实现夸界面组件动画
话不多说,上代码。
main.dart
代码如下
import 'package:flutter/material.dart';
import 'image_detail.dart';
void main() => runApp(const MyApp(title: "查看图片"));
class MyApp extends StatelessWidget {
final String _title;
const MyApp({super.key, title}) : _title = title ?? "Flutter Demo";
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: "Flutter Demo",
home: Scaffold(
appBar: AppBar(
title: Center(
child: Text(
_title,
style: const TextStyle(color: Colors.white),
)),
backgroundColor: Colors.blue,
),
body: MyHomePage(),
),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key});
Widget build(BuildContext context) {
return GridView(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
mainAxisSpacing: 8,
crossAxisSpacing: 8,
crossAxisCount: 2,
childAspectRatio: 16 / 9),
children: List.generate(20, (index) {
final String imageURL = "https://picsum.photos/500/500?random=$index";
return GestureDetector(
onTap: () {
Navigator.of(context).push(
PageRouteBuilder(
reverseTransitionDuration: const Duration(milliseconds: 300),
pageBuilder: (ctx, animation1, animation2) {
return FadeTransition(
opacity: animation1,
child: CheckImageDetail(imageURL),
);
},
),
);
},
child: Hero(
tag: imageURL,
child: Image.network(
imageURL,
fit: BoxFit.cover,
),
),
);
}),
);
}
}
相同目录下新建image_detail.dart
文件,该界面用于查看图片大图,代码如下。
import 'package:flutter/material.dart';
class CheckImageDetail extends StatelessWidget {
final String _imageURL;
const CheckImageDetail(this._imageURL, {super.key});
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.of(context).pop();
},
child: Scaffold(
backgroundColor: Colors.black,
body: Center(
child: Hero(
tag: _imageURL,
child: Image.network(
_imageURL,
fit: BoxFit.fitWidth,
),
),
),
),
);
}
}