![](/img/trans.png)
[英]How do you render an image from Firebase Storage using .map method?
[英]How to render image from Firebase without rebuilding?
我正在嘗試使用 Firebase 存儲在我的 flutter 應用程序中實現配置文件圖像選擇。 我使用 image_picker 獲取圖像並將其上傳到 Firebase,獲取下載鏈接並將下載鏈接添加到雲 firestore 中的imgsrc
字段,從那里我可以渲染 NetworkImage。
Center(
child: Stack(
children: [
buildImage(),
Positioned(
bottom: 5,
right: 5,
child: GestureDetector(
onTap: showPhotoAlertDialog,
child: buildEditIcon(Color(0xff407bff))),
),
],
),
),
當用戶沒有個人資料圖像時,如何獲取默認的Icons.person
類型圖像,否則如何從數據庫中獲取圖像? 我現在使用的代碼如下:
Widget buildImage() {
return CircleAvatar(
backgroundImage: NetworkImage(loggedInUser.imgsrc ??
'https://th.bing.com/th/id/R.945f33b643f2ceffcdae90fb57c61854?rik=XcI0SYBgSefoCA&riu=http%3a%2f%2fgetdrawings.com%2ffree-icon-bw%2fanonymous-avatar-icon-19.png&ehk=5n%2buJG66CeLQZsmhaMt8gag5rXuM3TdebAL6W35K1E4%3d&risl=&pid=ImgRaw&r=0'),
backgroundColor: Colors.grey[350],
radius: 100,
);
}
我創建了一個警報對話框小部件來選擇是從相機還是從圖庫中選擇圖像。
showPhotoAlertDialog() {
AlertDialog alert = AlertDialog(
title: Text("Upload from"),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextButton(
onPressed: () {
imageFromCamera()
.then((value) => uploadFile())
.whenComplete(() => postSource());
setState(() {}); ----->
},
child: Text("Upload from camera"),
),
TextButton(
onPressed: () {
imageFromGallery().then((value) => uploadFile());
postSource();
setState(() {});
},
child: Text("Upload from gallery"),
)
],
),
);
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
要將圖像上傳到存儲並將源發布到雲 firestore,我使用以下方法:
Future uploadFile() async {
if (file == null) return;
final fileName = path.basename(file!.path);
final destination = 'files/$fileName';
task = FirebaseApi.uploadFile(destination, file!);
setState(() {});
if (task == null) return;
final snapshot = await task!.whenComplete(() {});
urlDownload = await snapshot.ref.getDownloadURL();
print('Download-Link: $urlDownload');
}
postSource() async {
FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
await firebaseFirestore
.collection("users")
.doc(user?.uid)
.update({'imgsrc': urlDownload});
}
鏈接已正確上傳,我可以在我的NetworkImage
中獲取鏈接,但不會立即呈現。 我必須關閉父抽屜並再次打開它才能得到它。 我在發布源代碼后也調用了setState(){}
,但這沒有任何區別。 如何在不必關閉和打開抽屜的情況下獲取圖像?
任何幫助,將不勝感激! 謝謝
您還必須在 model class 或此 imgsrc 中更新圖像,也只需在 TextButton 的 onPressed 中的 setState 上方添加此行。
loggedInUser.imgsrc = urlDownload;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.