7. Flutter——GridView元件

Ymq.發表於2020-10-30

GridView 元件的常用引數

  • 當資料量很大的時候用矩陣方式排列比較清晰。此時我們可以用網格列表元件 GridView 實 現佈局。

  • 常用屬性:

名稱型別說明
scrollDirectionAxis滾動
paddingEdgeInsetsGeometry內邊距
resolvebool元件反向序列化
crossAxisSpacingdouble水平子 Widget 之間間距
mainAxisSpacingdouble垂直子 Widget 之間間距
crossAxisCountint一行的 Widget 數量
childAspectRatiodouble子 Widget 寬高比例
childrenint< Widget >[ ]
gridDelegateSliverGridDelegateWithFix edCrossAxisCount(常用) SliverGridDelegateWithMax CrossAxisExtent控制佈局主要用在 GridView.builder 裡面

GridView.count 實現網格佈局

import'package:flutter/material.dart';
import'res/listData.dart';

voidmain()=>runApp(MyApp());

classMyAppextendsStatelessWidget{ 
	@override
	 Widgetbuild(BuildContextcontext){  
	 	returnMaterialApp( 
	 		home:Scaffold( 
	 			appBar:AppBar(title:Text('FlutterDemo')), 
	 			body:LayoutContent(), 
	 		));
	 } 
	}

classLayoutContentextendsStatelessWidget{
	List<Widget>_getListData(){ 
		vartempList=listData.map((value){ 
			returnContainer( 
				child: Column( 
					children:<Widget>[ 
						Image.network(value["imageUrl"]), 
						SizedBox(height:12),	
						Text(value["title"],										
						textAlign:TextAlign.center,
						style:TextStyle(fontSize:20)), 
						], 
					), 
				    decoration:BoxDecoration( 
				    	border:Border.all( 
				    		color:Color.fromRGBO(230,230,230,0.9), 
				    		width:1.0 
				    		) 
				    	),
					);
	}); 
	returntempList.toList();
}

@override 
Widgetbuild(BuildContextcontext){  
	returnGridView.count( 
		padding:EdgeInsets.all(20), 
		crossAxisCount:2, 
		crossAxisSpacing:20, 
		mainAxisSpacing:20,  
		children:this._getListData(), 
		); 
	}
}

GridView.builder 實現網格佈局

import'package:flutter/material.dart';
import'res/listData.dart';

voidmain()=>runApp(MyApp());

classMyAppextendsStatelessWidget{ 
	@override Widgetbuild(BuildContextcontext){ 
		returnMaterialApp( 
			home:Scaffold( 
			appBar:AppBar(title:Text('FlutterDemo')), 
			body:LayoutContent(), 
			)); 
		} 
	}

classLayoutContentextendsStatelessWidget{
	Widget_getListData(context,index){ 
		returnContainer( 
			child: Column( 
				children:<Widget>[ 
					Image.network(listData[index]["imageUrl"]), 
					SizedBox(height:12), 
					Text(listData[index]["title"],
					textAlign: TextAlign.center,style:TextStyle(fontSize: 20)), 
					], 
				), 
			decoration:BoxDecoration( 
				border:Border.all( 
					color:Color.fromRGBO(230,230,230,0.9), 
					width:1.0 
				) 
			),
	);
}

@override 
Widgetbuild(BuildContextcontext){ 
	 returnGridView.builder( 
	 	itemCount:listData.length, 
	 	gridDelegate:SliverGridDelegateWithFixedCrossAxisCount(
	 			 //橫軸元素個數 
	 			 crossAxisCount:2, 
	 			 //縱軸間距 
	 			 mainAxisSpacing:20.0, 
	 			 //橫軸間距 
	 			 crossAxisSpacing:10.0, 
	 			 //子元件寬高長度比例 
	 			 childAspectRatio:1.0 
	 		), 
		itemBuilder:this._getListData, 
	  ); 
	}
}

相關文章