要為用戶創建的物件上傳影像,我將影像(由用戶選擇)存盤在陣列“imagesList”中作為檔案。當用戶單擊上傳(整個物件)時,以下方法將資料保存在 firebase 上:
TextButton(
onPressed: () async {
await uploadImage();
await jobService.createJob(Job(
titleTextEditorController.text.trim(),
category,
false,
false,
finalImageList));
},
child: Text('upload')),
List finalImageList 填充在第一個方法“uploadImage()”中。我用另一種方法獲取它來獲取 await 陳述句。代碼:
uploadImage() async {
for (int i = 0; i < imageList.length; i ) {
_imageFile = imageList[i];
String fileName = Path.basename(_imageFile!.path);
Reference reference =
FirebaseStorage.instance.ref().child('uploads/$fileName');
firebase_storage.SettableMetadata(
contentType: 'image/jpeg',
customMetadata: {'picked-file-path': fileName});
UploadTask uploadTask = reference.putFile(_imageFile!);
uploadTask.whenComplete(() async {
try {
imageUrl = await reference.getDownloadURL();
print('imageUrl' imageUrl);
finalImageList.add(imageUrl);
} catch (onError) {
print("Upload Error");
}
});
await Future.value(uploadTask)
.then((value) => {print('Upload file path ${value.ref.fullPath}')})
.onError((error, stackTrace) =>
{print('Upload file path error ${error.toString()}')});
}
}
但是該方法不夠快,無法將 imageUrl 存盤在 中finalImageList,因此影像在線但未連接到firebase 中的物件。是否有可能立即上傳或正確保存 imageUrl?還是我的代碼順序錯誤?
uj5u.com熱心網友回復:
FlutterFireUploadTask類 extends Future,這意味著您可以使用await它來等待上傳完成。
這意味著您可以更簡單地撰寫代碼:
await reference.putFile(_imageFile!);
imageUrl = await reference.getDownloadURL();
finalImageList.add(imageUrl);
print('Upload file path ${value.ref.fullPath}')
通過此更改,您uploadImage將僅在下載 URL 添加到finalImageList.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/401132.html
