crossAxisCount
- 定义GridView的列数(竖向时) / 定义GridView的行数(横向时)
crossAxisCount: 3,
scrollDirection
scrollDirection: Axis.horizontal,
scrollDirection: Axis.vertical,
crossAxisSpacing & mainAxisSpacing
- 定义GridView的item之间的间距(不包含与外界的间距)
crossAxisSpacing: 20,
mainAxisSpacing: 20,
childAspectRatio
- 定义GridView的item的宽高比 (滚动方向变化时随之变化)
childAspectRatio: 1/2,
创建GridView常用的两种方式
通过GridView.count创建
GridView.count(
crossAxisCount: 3,
scrollDirection: Axis.horizontal,
crossAxisSpacing: 20,
mainAxisSpacing: 20,
childAspectRatio: 1/2,
children: getListWidget(),
)
通过GridView.builder创建
GridView.builder(
itemCount: listData.length,
scrollDirection: Axis.horizontal,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 20,
mainAxisSpacing: 20,
childAspectRatio: 1.5 / 1,
),
itemBuilder: (BuildContext context, int index) {
return Column(
children: [
Image.network(listData[index]["imgUrl"]),
Text(listData[index]["title"])
],
);
},
)
示例
class GridViewBody extends StatelessWidget {
List<Widget> getListWidget() {
return listData.map((value) {
return Container(
width: 100,
height: 200,
color: Colors.blue,
child: Column(
children: [
Image.network(
imgUrl2,
fit: BoxFit.contain,
width: 50,
height: 50,
),
Text("标题")
],
));
}).toList();
}
@override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
padding: EdgeInsets.all(20),
height: 300,
child: GridView.count(
crossAxisCount: 3,
scrollDirection: Axis.horizontal,
crossAxisSpacing: 20,
mainAxisSpacing: 20,
childAspectRatio: 1/2,
children: getListWidget(),
),
);
}
}