class GridViewDemo extends StatefulWidget { GridViewDemo({Key key}) : super(key: key); @override _GridViewDemoState createState() => _GridViewDemoState(); } class _GridViewDemoState extends State<GridViewDemo> { @override Widget build(BuildContext context) { return Center( child: _buildGridViewCustom(), ); } /* Grid创建方法一:GridView.extend创建方法(根据横轴单个元素的最大宽度来计算一行显示几个) */ Widget _buildGridViewExtent() { return GridView.extent( //横轴的最大长度 根据屏幕的宽度除以这个宽度+间隙,就能算出一行显示几个 maxCrossAxisExtent: 180, children: _buildGridViewList(30), //垂直方向上的间隙 mainAxisSpacing: 10.0, //水平方向上的间隙 crossAxisSpacing: 10.0, //内边距 padding: EdgeInsets.all(10), ); } /* Grid创建方法二:GridView.count创建方法(指定一行有多少列) */ Widget _buildGridViewCount() { return GridView.count( //指定一行多少列 crossAxisCount: 3, children: _buildGridViewList(30), //垂直方向上的间隙 mainAxisSpacing: 10.0, //水平方向上的间隙 crossAxisSpacing: 10.0, //内边距 padding: EdgeInsets.all(10), ); } /* Grid创建方法三:GridView.custom创建方法(自定义网格) */ Widget _buildGridViewCustom() { return GridView.custom( // gridDelegate:SliverGridDelegateWithFixedCrossAxisCount 根据指定列数量显示grid,对应Gridview.count // gridDelegate:SliverGridDelegateWithMaxCrossAxisExtent 根据每个列宽度自定计算grid 对应Gridview.extend gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( //每行显示个数 crossAxisCount: 2, //纵向的间距 mainAxisSpacing: 4.0, //横向的间距 crossAxisSpacing: 4.0), childrenDelegate: SliverChildBuilderDelegate((Context, index) { return Image.network( 'http://www.5imoban.net/uploads/allimg/200619/1-200619222R40-L.jpg'); }, childCount: 30)); } /* Grid创建方法四:CustomScrollView懒加载的方法,性能好 */ Widget _buildGridViewSliver() { return CustomScrollView( primary: false, slivers: [ SliverPadding( padding: EdgeInsets.all(10.0), sliver: SliverGrid.count( //一行显示个数 crossAxisCount: 2, crossAxisSpacing: 10.0, children: _buildGridViewList(10), )) ], ); } //自动生成GridView的子元素 List<Container> _buildGridViewList(int count) { return List.generate( count, (int index) => Container( color: Colors.green, child: Image.network( 'http://www.5imoban.net/uploads/allimg/200619/1-200619222R40-L.jpg'), )); } }
部分素材资源来源网站,本站提供免费下载,如有侵权请联系站长马上删除!