标准的ListView构造函数适用于小列表。 为了处理包含大量数据的列表,最好使用ListView.builder构造函数。

ListView的构造函数需要一次创建所有项目,但ListView.builder的构造函数不需要,它将在列表项滚动到屏幕上时创建该列表项。

1. 创建一个数据源

首先,我们需要一个数据源来。例如,您的数据源可能是消息列表、搜索结果或商店中的产品。大多数情况下,这些数据将来自互联网或数据库。

在这个例子中,我们将使用List.generate构造函数生成拥有10000个字符串的列表

  1. final items = new List<String>.generate(10000, (i) => "Item $i");

2. 将数据源转换成Widgets

为了显示我们的字符串列表,我们需要将每个字符串展现为一个Widget !

这正是ListView.builder发挥作用的地方。在我们的例子中,我们将每一行显示一个字符串:

  1. new ListView.builder(
  2. itemCount: items.length,
  3. itemBuilder: (context, index) {
  4. return new ListTile(
  5. title: new Text('${items[index]}'),
  6. );
  7. },
  8. );

完整的例子

  1. import 'package:flutter/foundation.dart';
  2. import 'package:flutter/material.dart';
  3. void main() {
  4. runApp(new MyApp(
  5. items: new List<String>.generate(10000, (i) => "Item $i"),
  6. ));
  7. }
  8. class MyApp extends StatelessWidget {
  9. final List<String> items;
  10. MyApp({Key key, @required this.items}) : super(key: key);
  11. @override
  12. Widget build(BuildContext context) {
  13. final title = 'Long List';
  14. return new MaterialApp(
  15. title: title,
  16. home: new Scaffold(
  17. appBar: new AppBar(
  18. title: new Text(title),
  19. ),
  20. body: new ListView.builder(
  21. itemCount: items.length,
  22. itemBuilder: (context, index) {
  23. return new ListTile(
  24. title: new Text('${items[index]}'),
  25. );
  26. },
  27. ),
  28. ),
  29. );
  30. }
  31. }