Flutter 组件基础 ——GridView#
GridView 是网格布局,类似于 iOS 中的 UICollectionView,可设置每行多少个、单个对象的宽高比、对象水平方向的间距、垂直方向的间距等等。
GridView 的常用属性#
- GridView
- scrollDirection: 滑动方向
- Axis.horizontal: 水平方向滑动
- Axis.vertical: 垂直方向滑动,默认为这个。
- padding: GridView 相对于父视图的边距
- crossAxisCount: 每行多少个
- mainAxisSpacing: 与滑动方向垂直的方向的间距,eg: 当横向滑动时,这个代表垂直方向对象之间的间距;
- crossAxisSpacing: 与滑动方向平行的方向的间距,eg: 当横向滑动时,这个代表水平方向对象之间的间距;
- childAspectRatio:单个元素的宽高比 (或者高宽比),当 scrollDirection 为 vertical 时,代表宽高比;当 scrollDirection 为 horizontal 时,代表高宽比。
- scrollDirection: 滑动方向
简单使用#
代码如下:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'GridView widget',
home: Scaffold(
body: GridView.count(
scrollDirection: Axis.vertical,
childAspectRatio: 2,
padding: const EdgeInsets.all(40.0),
crossAxisSpacing: 10.0,
mainAxisSpacing: 20.0,
crossAxisCount: 2,
children: <Widget>[
Container(
padding: const EdgeInsets.all(8),
child: const Text("He'd have you all unravel at the"),
color: Colors.teal[100],
),
Container(
padding: const EdgeInsets.all(8),
child: const Text('Heed not the rabble'),
color: Colors.teal[200],
),
Container(
padding: const EdgeInsets.all(8),
child: const Text('Sourd of screams but the'),
color: Colors.teal[300],
),
Container(
padding: const EdgeInsets.all(8),
child: const Text('Who scream'),
color: Colors.teal[400],
),
Container(
padding: const EdgeInsets.all(8),
child: const Text('Revolution is coming...'),
color: Colors.teal[500],
),
Container(
padding: const EdgeInsets.all(8),
child: const Text('Revolution, they...'),
color: Colors.teal[600],
),
],
),
));
}
}
效果如下:
动态列表#
代码如下:
class MyGridView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GridView.builder(
padding: EdgeInsets.all(40.0),
scrollDirection: Axis.horizontal,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 20.0,
crossAxisSpacing: 10.0,
childAspectRatio: 2.0),
itemCount: 6,
itemBuilder: (BuildContext context, int index) {
return Card(
color: Colors.amber,
child: Center(
child: Text('$index'),
),
);
});
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: new AppBar(
title: new Text('GridView builder'),
),
body: MyGridView(),
),
);
}
}
效果如下: