九宫格看图,效果如下图
import 'package:flutter/material.dart';
import 'dart:math';
// ignore: must_be_immutable
class NinePicture extends StatelessWidget {
List<Map<String, String>> list = [];
NinePicture(List<Map<String, String>> list) {
this.list = list;
}
void showPhoto(BuildContext context, Map<String, String> img) {
Navigator.push(context,
MaterialPageRoute<void>(builder: (BuildContext context) {
return GestureDetector(
child: SizedBox.expand(
child: Hero(
tag: img['tag'],
child: Image.asset(
img['img'],
fit: BoxFit.contain,
),
),
),
onTap: () {
Navigator.maybePop(context);
},
);
}));
}
@override
Widget build(BuildContext context) {
int _crossAxisCount = 1;
if (list.length == 1) {
_crossAxisCount = 1;
} else if (list.length == 2) {
_crossAxisCount = 2;
} else {
_crossAxisCount = 3;
}
return Container(
width: double.infinity,
height: (MediaQuery.of(context).size.width / _crossAxisCount + 2.0) *
(list.length / _crossAxisCount).ceil(),
child: GridView.count(
physics: ClampingScrollPhysics(),
crossAxisCount: _crossAxisCount,
mainAxisSpacing: 2.0,
crossAxisSpacing: 2.0,
padding: const EdgeInsets.all(4.0),
children: list.map(
(Map<String, String> img) {
img['tag'] = Random().nextInt(100000000).toString();
print(img['tag']);
return GestureDetector(
onTap: () {
showPhoto(context, img);
},
child: Hero(
tag: img['tag'],
child: ClipRRect(
child: Image.asset(
img['img'],
fit: BoxFit.cover,
),
borderRadius: BorderRadius.circular(8),
),
),
);
},
).toList(),
),
);
}
}
获得每行显示的个数
int _crossAxisCount = 1;
if (list.length == 1) {
_crossAxisCount = 1;
} else if (list.length == 2) {
_crossAxisCount = 2;
} else {
_crossAxisCount = 3;
}
计算高度
(MediaQuery.of(context).size.width / _crossAxisCount + 2.0) *
(list.length / _crossAxisCount).ceil()