標準的ListView構造函數適用于小列表。 為了處理包含大量數據的列表,最好使用ListView.builder構造函數。
ListView的構造函數需要一次創(chuàng)建所有項目,但ListView.builder的構造函數不需要,它將在列表項滾動到屏幕上時創(chuàng)建該列表項。
1. 創(chuàng)建一個數據源
首先,我們需要一個數據源來。例如,您的數據源可能是消息列表、搜索結果或商店中的產品。大多數情況下,這些數據將來自互聯網或數據庫。
在這個例子中,我們將使用List.generate構造函數生成擁有10000個字符串的列表
final items = new List<String>.generate(10000, (i) => "Item $i");
2. 將數據源轉換成Widgets
為了顯示我們的字符串列表,我們需要將每個字符串展現為一個Widget !
這正是ListView.builder發(fā)揮作用的地方。在我們的例子中,我們將每一行顯示一個字符串
new ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return new ListTile(
title: new Text('${items[index]}'),
);
},
);
完整的例子
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp(
items: new List<String>.generate(10000, (i) => "Item $i"),
));
}
class MyApp extends StatelessWidget {
final List<String> items;
MyApp({Key key, @required this.items}) : super(key: key);
@override
Widget build(BuildContext context) {
final title = 'Long List';
return new MaterialApp(
title: title,
home: new Scaffold(
appBar: new AppBar(
title: new Text(title),
),
body: new ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return new ListTile(
title: new Text('${items[index]}'),
);
},
),
),
);
}
}