在某些情况下,您可能希望将item显示为网格,而不是一个普通列表。对于这需求,我们可以使用GridView Widget。

使用网格的最简单方法是使用GridView.count构造函数,它允许我们指定行数或列数。

在这个例子中,我们将生成一个包含100个widget的list,在网格中显示它们的索引。这将帮助我们观察GridView如何工作。

  1. new GridView.count(
  2. // Create a grid with 2 columns. If you change the scrollDirection to
  3. // horizontal, this would produce 2 rows.
  4. crossAxisCount: 2,
  5. // Generate 100 Widgets that display their index in the List
  6. children: new List.generate(100, (index) {
  7. return new Center(
  8. child: new Text(
  9. 'Item $index',
  10. style: Theme.of(context).textTheme.headline,
  11. ),
  12. );
  13. }),
  14. );

完整的例子

  1. import 'package:flutter/material.dart';
  2. void main() {
  3. runApp(new MyApp());
  4. }
  5. class MyApp extends StatelessWidget {
  6. @override
  7. Widget build(BuildContext context) {
  8. final title = 'Grid List';
  9. return new MaterialApp(
  10. title: title,
  11. home: new Scaffold(
  12. appBar: new AppBar(
  13. title: new Text(title),
  14. ),
  15. body: new GridView.count(
  16. // Create a grid with 2 columns. If you change the scrollDirection to
  17. // horizontal, this would produce 2 rows.
  18. crossAxisCount: 2,
  19. // Generate 100 Widgets that display their index in the List
  20. children: new List.generate(100, (index) {
  21. return new Center(
  22. child: new Text(
  23. 'Item $index',
  24. style: Theme.of(context).textTheme.headline,
  25. ),
  26. );
  27. }),
  28. ),
  29. ),
  30. );
  31. }
  32. }