Flutter中ListView加載圖片數(shù)據(jù)的優(yōu)化

在使用ListView懶加載模式時,當(dāng)ListView的Item中有圖片信息時,在快速滾動過程中會大量的浪費(fèi)流量與內(nèi)存,甚至?xí)斐稍跐L動過程中頁面的卡頓效果。
在這里提出優(yōu)化方案,當(dāng)開始滾動時不加載圖片,滾動結(jié)束后再加載圖片,這個優(yōu)化方案實現(xiàn)的效果如下圖所示,在快速滑動列表數(shù)據(jù)時,圖片未加載,運(yùn)行內(nèi)存無明顯波動。

實現(xiàn)代碼如下:
class ListViewUsePage13 extends StatefulWidget {
? @override
? State<StatefulWidget> createState() {
? ? return ScrollHomePageState();
? }
}
class ScrollHomePageState extends State {
? ///加載圖片的標(biāo)識
? bool isLoadingImage = true;
? ///網(wǎng)絡(luò)圖片地址
? String netImageUrl =
? ? ? "https://images.gitee.com/uploads/images/2020/0602/203000_9fa3ddaa_568055.png";
? @override
? Widget build(BuildContext context) {
? ? return Scaffold(
? ? ? appBar: new AppBar(
? ? ? ? title: Text("詳情"),
? ? ? ),
? ? ? ///列表
? ? ? body: NotificationListener(
? ? ? ? ///子Widget中的滾動組件滑動時就會分發(fā)滾動通知
? ? ? ? child: buildListView(),
? ? ? ? ///每當(dāng)有滑動通知時就會回調(diào)此方法
? ? ? ? onNotification: notificationFunction,
? ? ? ),
? ? );
? }
? bool notificationFunction(Notification notification) {
? ? ///通知類型
? ? switch (notification.runtimeType) {
? ? ? case ScrollStartNotification:
? ? ? ? print("開始滾動");
? ? ? ? ///在這里更新標(biāo)識 刷新頁面 不加載圖片
? ? ? ? isLoadingImage = false;
? ? ? ? break;
? ? ? case ScrollUpdateNotification:
? ? ? ? print("正在滾動");
? ? ? ? break;
? ? ? case ScrollEndNotification:
? ? ? ? print("滾動停止");
? ? ? ? ///在這里更新標(biāo)識 刷新頁面 加載圖片
? ? ? ? setState(() {
? ? ? ? ? isLoadingImage = true;
? ? ? ? });
? ? ? ? break;
? ? ? case OverscrollNotification:
? ? ? ? print("滾動到邊界");
? ? ? ? break;
? ? }
? ? return true;
? }
? ListView buildListView() {
? ? return ListView.separated(
? ? ? itemCount: 10000, //子條目個數(shù)
? ? ? ///構(gòu)建每個條目
? ? ? itemBuilder: (BuildContext context, int index) {
? ? ? ? if (isLoadingImage) {
? ? ? ? ? ///這時將子條目單獨(dú)封裝在了一個StatefulWidget中
? ? ? ? ? return Image.network(
? ? ? ? ? ? netImageUrl,
? ? ? ? ? ? width: 100,
? ? ? ? ? ? height: 100,
? ? ? ? ? ? fit: BoxFit.fitHeight,
? ? ? ? ? );
? ? ? ? } else {
? ? ? ? ? return Container(
? ? ? ? ? ? height: 100,
? ? ? ? ? ? width: 100,
? ? ? ? ? ? child: Text("加載中..."),
? ? ? ? ? ); //占位
? ? ? ? }
? ? ? },
? ? ? ///構(gòu)建每個子Item之間的間隔Widget
? ? ? separatorBuilder: (BuildContext context, int index) {
? ? ? ? return new Divider();
? ? ? },
? ? );
? }
}