团队作业博客(十)实现查看图片
import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';
void main() {
runApp(MaterialApp(
home: Picture1(),
));
}
class Picture1 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: PictureListPage(),
);
}
}
class PictureListPage extends StatelessWidget {
final List<String> imagePaths = [
'assets/images/picture0.jpg',
'assets/images/picture1.jpg',
'assets/images/picture2.jpg',
'assets/images/picture3.jpg',
'assets/images/picture4.jpg',
'assets/images/picture5.jpg',
'assets/images/picture6.jpg',
// 确保图像数量为偶数,或者你可以在末尾添加更多的图像或占位符
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('图片列表'),
),
body: GridView.count(
crossAxisCount: 2, // 每行两列
children: imagePaths.map((path) => _buildPictureItem(context, path)).toList(),
),
);
}
Widget _buildPictureItem(BuildContext context, String imagePath) {
return Card(
child: InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PhotoViewWrapper(imageProvider: AssetImage(imagePath)),
),
);
},
child: Image.asset(
imagePath,
fit: BoxFit.cover,
width: MediaQuery.of(context).size.width / 2 - 16, // 减去左右padding的宽度
alignment: Alignment.center,
),
),
);
}
}
class PhotoViewWrapper extends StatelessWidget {
final ImageProvider imageProvider;
PhotoViewWrapper({required this.imageProvider});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('查看图片'),
),
body: Center(
child: PhotoView(
imageProvider: imageProvider,
loadingBuilder: (context, progress) => Center(
child: CircularProgressIndicator(),
),
errorBuilder: (context, error, stackTrace) => Center(
child: Icon(Icons.error),
),
),
),
);
}
}