简单介绍
GridView是一个网格布局的Widget。
用法
1、GridView.count
class GridViewCountDemo extends StatelessWidget {
List<Widget> _gridItems(int length) {
return List.generate(length, (int index) {
return Container(
alignment: Alignment(0.0, 0.0),
color: Colors.grey,
child: Text(
'Item $index',
style: TextStyle(
color: Colors.red,
fontSize: 20.0,
),
),
);
});
}
@override
Widget build(BuildContext context) {
return GridView.count(
crossAxisCount: 2, /
crossAxisSpacing: 10.0,
mainAxisSpacing: 10.0,
children: _gridItems(100),
);
}
}
2、GridView.extent
class GridViewExtentDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
List<Widget> _gridItems(int length) {
return List.generate(length, (int index) {
return Container(
color: Colors.green,
alignment: Alignment(0.0, 0.0),
child: Text(
'item $index',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
);
});
}
return GridView.extent(
maxCrossAxisExtent: 200.0, // 相当于网格宽度
crossAxisSpacing: 10.0,
mainAxisSpacing: 10.0,
children: _gridItems(50),
);
}
}
3、GridView.builder
网格数量可以自由配置
class GridViewBuildDemo extends StatelessWidget {
Widget _gridItem(BuildContext context, int index) {
return Container(
child: Image.network(
posts[index].imageUrl,
fit: BoxFit.cover,
),
);
}
@override
Widget build(BuildContext context) {
return GridView.builder(
padding: EdgeInsets.all(20.0),
itemCount: posts.length,
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
// crossAxisCount: 3,
maxCrossAxisExtent: 200,
crossAxisSpacing: 10.0,
mainAxisSpacing: 10.0,
),
itemBuilder: _gridItem);
}
}