Flutter ListView加載圖片優化(滑動不加載,停止滑動加載)
前言:為了更好的減小網路的帶寬,使得串列更加流暢,我們需要了解懶加載,也稱延遲加載, 面試真題:flutter如何實作懶加載?
本章,我們會實作wechat朋友圈的優化功能,即當頁面在滑動時不加載圖片,在界面停止滑動時加載圖片,
效果圖:
滑動時:
停止滑動開始加載:

1.了解widget通知監聽:NotificationListener
NotificationListener屬性:
-
child:widget -
onNotification:NotificationListenerCallback<Notification> 回傳值true表示消費掉當前通知不再向上一級NotificationListener傳遞通知,false則會再向上一級NotificationListener傳遞通知;這里需要注意的是通知是由下而上去傳遞的,所以才會稱作冒泡通知
2.需要一個bool來控制是否加載
///加載圖片的標識
bool isLoadingImage = true;
3.撰寫傳遞通知的方法,使其作用于NotificationListener
bool notificationFunction(Notification notification) {
///通知型別
switch (notification.runtimeType) {
case ScrollStartNotification:
print("開始滾動");
///在這里更新標識 重繪頁面 不加載圖片
isLoadingImage = false;
break;
case ScrollUpdateNotification:
print("正在滾動");
break;
case ScrollEndNotification:
print("滾動停止");
///在這里更新標識 重繪頁面 加載圖片
setState(() {
isLoadingImage = true;
});
break;
case OverscrollNotification:
print("滾動到邊界");
break;
}
return true;
}
4.根據bool值加載不同的組件
ListView buildListView() {
return ListView.separated(
itemCount: 1000, //子條目個數
///構建每個條目
itemBuilder: (BuildContext context, int index) {
if (isLoadingImage) {
///這時將子條目單獨封裝在了一個StatefulWidget中
return Image.network(
netImageUrl,
width: 100,
height: 100,
fit: BoxFit.fitHeight,
);
} else {
return Container(
height: 100,
width: 100,
child: Text("加載中..."),
); //占位
}
},
///構建每個子Item之間的間隔Widget
separatorBuilder: (BuildContext context, int index) {
return new Divider();
},
);
}
完整代碼:
class ScrollHomePageState extends State {
///加載圖片的標識
bool isLoadingImage = true;
///網路圖片地址
String netImageUrl =
"https://img.uj5u.com/2021/09/03/261395031914263.png";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: Text("詳情"),
),
///串列
body: NotificationListener(
///子Widget中的滾動組件滑動時就會分發滾動通知
child: buildListView(),
///每當有滑動通知時就會回呼此方法
onNotification: notificationFunction,
),
);
}
bool notificationFunction(Notification notification) {
///通知型別
switch (notification.runtimeType) {
case ScrollStartNotification:
print("開始滾動");
///在這里更新標識 重繪頁面 不加載圖片
isLoadingImage = false;
break;
case ScrollUpdateNotification:
print("正在滾動");
break;
case ScrollEndNotification:
print("滾動停止");
///在這里更新標識 重繪頁面 加載圖片
setState(() {
isLoadingImage = true;
});
break;
case OverscrollNotification:
print("滾動到邊界");
break;
}
return true;
}
ListView buildListView() {
return ListView.separated(
itemCount: 1000, //子條目個數
///構建每個條目
itemBuilder: (BuildContext context, int index) {
if (isLoadingImage) {
///這時將子條目單獨封裝在了一個StatefulWidget中
return Image.network(
netImageUrl,
width: 100,
height: 100,
fit: BoxFit.fitHeight,
);
} else {
return Container(
height: 100,
width: 100,
child: Text("加載中..."),
); //占位
}
},
///構建每個子Item之間的間隔Widget
separatorBuilder: (BuildContext context, int index) {
return new Divider();
},
);
}
}
是不是很簡單~
歡迎留言糾正 ~ 不妨給個點贊哈哈
我是阿T一個幽默的程式員 我們下期再見~
添加我為你的好友,領取原始碼以及Flutter學習資料~

加入我們吧,一起學習,一起進步~

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/297173.html
標籤:其他
