長清單的處理
標準的 ListView
建構式函式適用於短清單,對於具有大量清單項的長清單,需要用 ListView.builder
建構式函式來建立。
與標準的 ListView
建構式函式需要一次性建立所有清單項不同的是,
ListView.builder
建構式函式只在清單項從螢幕外滑入螢幕時才去建立清單項。
1. 建立資料來源
首先,需要獲取清單的資料來源。例如,資料來源可以是訊息集、搜尋結果集或者商店商品集。大部分情況下,這些資料來自於網路請求或者資料庫獲取。
在下面的例子,使用 List.generate
建構式函式生成包含 10,000 個字串的集合。
List<String>.generate(10000, (i) => 'Item $i'),
2. 將資料來源渲染成元件
為了將字串集合展示出來,需要透過 ListView.builder
把集合中的每個字串都渲染成元件。
在下面的例子中,將會把每個字串用單行清單項顯示在清單中。
ListView.builder(
itemCount: items.length,
prototypeItem: ListTile(
title: Text(items.first),
),
itemBuilder: (context, index) {
return ListTile(
title: Text(items[index]),
);
},
)
互動式範例
import 'package:flutter/material.dart';
void main() {
runApp(
MyApp(
items: List<String>.generate(10000, (i) => 'Item $i'),
),
);
}
class MyApp extends StatelessWidget {
final List<String> items;
const MyApp({super.key, required this.items});
@override
Widget build(BuildContext context) {
const title = 'Long List';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: const Text(title),
),
body: ListView.builder(
itemCount: items.length,
prototypeItem: ListTile(
title: Text(items.first),
),
itemBuilder: (context, index) {
return ListTile(
title: Text(items[index]),
);
},
),
),
);
}
}
Children’s extent
To specify each item’s extent, you can use either itemExtent
or prototypeItem
.
Specifying either is more efficient than letting the children determine their own extent
because the scrolling machinery can make use of the foreknowledge of the children’s
extent to save work, for example when the scroll position changes drastically.