文章目录
一、GridView 网格布局简介
二、完整代码示例
三、相关资源
一、GridView 网格布局简介
GridView 可用于显示网格布局 ;
一般使用 GridView.count 函数构造一个 GridView 组件 ;
GridView.count 构造函数如下 :
GridView.count({ Key? key, Axis scrollDirection = Axis.vertical, bool reverse = false, ScrollController? controller, bool? primary, ScrollPhysics? physics, bool shrinkWrap = false, EdgeInsetsGeometry? padding, required int crossAxisCount, // 每行显示元素个数 double mainAxisSpacing = 0.0, double crossAxisSpacing = 0.0, double childAspectRatio = 1.0, bool addAutomaticKeepAlives = true, bool addRepaintBoundaries = true, bool addSemanticIndexes = true, double? cacheExtent, List<Widget> children = const <Widget>[], // 显示的组件列表 int? semanticChildCount, DragStartBehavior dragStartBehavior = DragStartBehavior.start, ScrollViewKeyboardDismissBehavior keyboardDismissBehavior = ScrollViewKeyboardDismissBehavior.manual, String? restorationId, Clip clipBehavior = Clip.hardEdge, })
一般只需要设置 required int crossAxisCount , List<Widget> children = const <Widget>[] 两个参数即可显示出列表组件 ;
/// 网格组件 GridView.count( /// 指定一行显示多少列 crossAxisCount: 4, /// 指定显示的 List<Widget> children: _buildList(), ),
二、完整代码示例
import 'package:flutter/material.dart'; const NAMES = [ '宋江', '卢俊义', '吴用', '公孙胜', '关胜', '林冲', '秦明', '呼延灼', '花荣', '柴进', '李应', '朱仝', '鲁智深', '武松', '董平', '张清', '杨志', '徐宁', '索超', '岱宗', '刘唐', '李逵', '史进', '穆弘' '雷横' ]; /// 垂直列表 void main() { runApp(MyApp()); } class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { @override Widget build(BuildContext context) { /// 材料设计主题 return MaterialApp( home: Scaffold( appBar: AppBar( /// 标题组件 title: Text("GridView 示例"), ), /// 网格组件 body: GridView.count( /// 指定一行显示多少列 crossAxisCount: 4, /// 指定显示的 List<Widget> children: _buildList(), ), ), ); } /// 创建列表 List<Widget> _buildList(){ /// 遍历 NAMES 数组 /// 调用 map 方法遍历数组元素 return NAMES.map((name) => _generateWidget(name)).toList(); } Widget _generateWidget(name){ return Container( height: 80, margin: EdgeInsets.only(bottom: 5, right: 5), alignment: Alignment.center, decoration: BoxDecoration(color: Colors.black), child: Text( name, style: TextStyle( color: Colors.yellowAccent, fontSize: 20 ), ), ); } }
执行结果 :