[英]How to fix flutter widget flickering?
我正在嘗試將 firebase 存儲中的圖像加載到我的應用程序,但是我遇到了一個奇怪的問題,即個人資料頁面(加載此圖像的位置)一直閃爍。 圖像加載正常,但整個小部件不斷閃爍。 經過一些調試后,我已將問題縮小到在 function getProfilePic() 中調用的 setState(),但是我不知道是 function 本身還是我對上述 ZC1C425268E687A984F1C1 的調用
PS fileURL 或 picRef.getDownloadURL() 沒有問題,因為我也使用隨機互聯網圖像對此進行了測試,並且得到了相同的閃爍。
class profileTab extends StatefulWidget {
@override
_profileTabState createState() => _profileTabState();
}
class _profileTabState extends State<profileTab> {
User user = FirebaseAuth.instance.currentUser;
String _image = "https://picsum.photos/250?image=9";
Reference picRef = FirebaseStorage.instance.ref().child(FirebaseAuth.instance.currentUser.uid);
Future<Widget> getProfilePic() async {
await picRef.getDownloadURL().then((fileURL){
setState(() {
_image = fileURL;
});
});
}
@override
Widget build(BuildContext context) {
getProfilePic();
return StreamBuilder(
stream: FirebaseFirestore.instance.collection('users').doc(user.uid).snapshots(),
builder: (context, snapshot){
if (snapshot.connectionState == ConnectionState.active){
return ListView(
children: <Widget>[
SizedBox(height: 100.0,),
CircleAvatar(
radius: 100.0,
backgroundColor: Colors.lightBlueAccent,
child: ClipOval(
child: SizedBox(
width: 180.0,
height: 180.0,
child: Image.network(_image,fit: BoxFit.fill,),
),
),
),
SizedBox(height: 30.0,),
Center(child: Text("Name: " + snapshot.data.data()['name'],textScaleFactor: 3.0,)),
]
);
}
else {
return CircularProgressIndicator();
}
},
);
}
}
getProfilePic 正在通過調用 setState 重繪小部件。 setState 調用調用 getProfilePic 的 build 方法。
因此,當第一次調用 build 方法時,我們調用 getProfilePic 再次更新小部件樹。 修復:如果 _image 為 null,則在 getProfilePic 中添加檢查以調用 setState,這將只重繪一次小部件。 如果你使用 Image.network 會更好。 你可以參考這個https://www.woolha.com/tutorials/flutter-display-image-from-network-url-show-loading
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.