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(),
),
);
}
}
效果如下: