有时候,你可能希望用网格来展示内容,而不是一条接着一条的普通列表来展示。在本文当中,我们将采用 GridView Widget。
用网格展示数据最简单的方式,就是通过使用 GridView.count 构造方法,因为它允许我们指定有多少行多少列。
在这个例子中,我们将创建一个包含有 100 个 Widget 的 List,每个 Widget 将展示它在 List 中的索引。这将帮助我们想象 GridView 是如何工作的。
GridView.count(// 创建一个两列的网格。如果你把 scrollDirection 改成了 horizontal,(Create a grid with 2 columns. If you change the scrollDirection to)// 则展示成两行。(horizontal, this would produce 2 rows.)crossAxisCount: 2,// 创建 100 个展示了索引的 Widget(Generate 100 Widgets that display their index in the List)children: List.generate(100, (index) {return Center(child: Text('Item $index',style: Theme.of(context).textTheme.headline,),);}),);
完整示例
import 'package:flutter/material.dart';void main() {runApp(MyApp());}class MyApp extends StatelessWidget {@overrideWidget build(BuildContext context) {final title = 'Grid List';return MaterialApp(title: title,home: Scaffold(appBar: AppBar(title: Text(title),),body: GridView.count(// 创建一个两列的网格。如果你把 scrollDirection 改成了 horizontal,(Create a grid with 2 columns. If you change the scrollDirection to)// 则展示成两行。(horizontal, this would produce 2 rows.)crossAxisCount: 2,// 创建 100 个展示了索引的 Widget(Generate 100 Widgets that display their index in the List)children: List.generate(100, (index) {return Center(child: Text('Item $index',style: Theme.of(context).textTheme.headline,),);}),),),);}}
当前内容版权归 flutter-io.cn 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 flutter-io.cn .