认识GridView组件并简单使用
先看一个简单的例子,使用Text组件作为GrideView的item:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "GridView",
home: Scaffold(
appBar: AppBar(
title: Text("GridView Widget"),
),
body: GridView.count(
crossAxisCount: 3,
padding: EdgeInsets.all(10.0),
crossAxisSpacing: 10.0,
children: <Widget>[
const Text("this is 1 item"),
const Text("this is 2 item"),
const Text("this is 3 item"),
const Text("this is 4 item"),
const Text("this is 5 item"),
],
),
),
);
}
}
效果如图:
使用
GridView.count()
方法创建GridView组件,
- padding:表示内边距
- crossAxisCount:表示每行显示的网格个数
- crossAxisSpacing:表示每个网格之间的间距。
这样并不太直观,下面使用图片组件作为GrideView的item:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "GridView",
home: Scaffold(
appBar: AppBar(
title: Text("GridView Widget"),
),
body: GridView(
padding: EdgeInsets.all(1.0),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
mainAxisSpacing: 2.0,
crossAxisSpacing: 2.0,
childAspectRatio: 0.75),
children: <Widget>[
Image.network(
"http://img5.mtime.cn/mt/2019/02/21/095918.47882172_270X405X4.jpg",
fit: BoxFit.cover),
Image.network(
"http://img5.mtime.cn/mt/2019/01/25/100901.82440600_270X405X4.jpg",
fit: BoxFit.cover),
Image.network(
"http://img5.mtime.cn/mg/2019/02/19/095714.33859824_270X405X4.jpg",
fit: BoxFit.cover),
Image.network(
"http://img5.mtime.cn/mt/2019/01/25/105549.53627008_270X405X4.jpg",
fit: BoxFit.cover),
Image.network(
"http://img5.mtime.cn/mt/2019/03/01/142658.85498591_270X405X4.jpg",
fit: BoxFit.cover),
Image.network(
"http://img5.mtime.cn/mt/2019/01/09/171109.88229500_270X405X4.jpg",
fit: BoxFit.cover),
Image.network(
"http://img5.mtime.cn/mg/2019/02/26/103754.10526344_270X405X4.jpg",
fit: BoxFit.cover)
],
)),
);
}
}
效果如图:
imgGrid.jpg
- childAspectRatio: 表示宽高比,即宽是高的多少倍,0.75=3/4
- mainAxisSpacing:可以理解为行间距
- crossAxisSpacing:可以理解为列间距
网友评论