Flutter開發中,表格元件是經常要用到的,表格展示資料也是App開發過程中不可缺少的需求的功能,其實Gridview的屬性和ListView的屬性很接近,那麼本篇文章就來聊聊Flutter開發中表格元件Gridview的簡單使用。
Gridview常用的幾種方式:
1、GridView.count(@required int crossAxisCount)
GridView.count的使用,需要傳的是int類型的參數,也就是建立固定數量的item,crossAxisCount表示橫軸item的個數(系統預設是橫軸);
2、GridView.extent(@required double maxCrossAxisExtent)
GridView.extent的使用,需要傳的是double類型的參數,也就是建立橫軸上最大可容納的item,maxCrossAxisExtent表示橫軸item的最大寬度;
3、GridView.builder(@required this.gridDelegate,@required IndexedWidgetBuilder itemBuilder)
适用于widget數量多的時候,通過GridView.builder的使用,動态的建立widget,itemBuilder表示子widget構造器;
4、GridView.custom(@required this.gridDelegate,@required this.childrenDelegate)
GridView.custom的使用,通過兩個代理方法gridDelegate和childrenDelegate來建立Gridview,其中gridDelegate是進行布局的代理,控制每列或每行的子widget的數量,以及上下左右間距和寬高比例;childrenDelegate的代理方法有兩種實作方式,在使用的時候需要注意二者的差別。
Gridview的簡單使用的執行個體,具體操作如下所示:
1、dart檔案的具體實作源碼
import 'package:flutter/material.dart';
import 'package:portal/model/workspace_item_data.dart';
import 'package:portal/widgets/widget_warpper.dart';
class WorkspacePage extends StatefulWidget {
@override
_WorkspacePageState createState() => _WorkspacePageState();
}
class _WorkspacePageState extends State<WorkspacePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: buildAppBar(context, title: "工作台", leading: Container()),
body: GridView.builder(
itemCount: listData.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3, mainAxisSpacing: 10, crossAxisSpacing: 10, childAspectRatio: 0.9),
padding: EdgeInsets.all(10),
itemBuilder: getItem,
),
);
}
Widget getItem(context, index) {
return Container(
decoration:
BoxDecoration(border: Border.all(color: Colors.black12, width: 2)),
child: Column(
children: [
Image.network(listData[index]['imageUrl']),
SizedBox(
height: 10,
),
Text(listData[index]['title'])
],
),
);
}
}
複制
2、資料源檔案,Gridview的itemCount的資料源(為了展現清單效果,刻意多造了幾條資料):
List listData=[
{
"title": '行政審批',
"author": 'Mohamed Chahin',
"imageUrl": 'https://www.itying.com/images/flutter/1.png',
},
{
"title": '協同辦公',
"author": 'Google',
"imageUrl": 'https://www.itying.com/images/flutter/2.png',
},
{
"title": '實名認證',
"author": 'Alibaba',
"imageUrl": 'https://www.itying.com/images/flutter/3.png',
},
{
"title": '會議室',
"author": 'Mohamed Chahin',
"imageUrl": 'https://www.itying.com/images/flutter/4.png',
},
{
"title": '企業郵箱',
"author": 'Mohamed Chahin',
"imageUrl": 'https://www.itying.com/images/flutter/5.png',
},
{
"title": '測溫',
"author": 'Mohamed Chahin',
"imageUrl": 'https://www.itying.com/images/flutter/6.png',
},
{
"title": '企業文化',
"author": 'Mohamed Chahin',
"imageUrl": 'https://www.itying.com/images/flutter/7.png',
},];
複制
3、效果圖如下所示: