我正在向 firebase storage 添加一個檔案。獲取影像的firebase url后,我使用setState將其設定為另一個字串(fileUrl),然后將其添加到Firestore資料庫。問題是它沒有更新到 firebase url 并且 String fileUrl 仍然有它的初始化值。我用來添加檔案并將其添加到 Firestore 資料庫的方式,我不確定如何修復。
首先我選擇一個檔案:
...
String fileUrl = 'temp';
...
Future uploadFile() async {
if (file == null) return Container();
final fileName = basename(file!.path);
final destination = 'files/$fileName';
task = FirebaseApi.uploadFile(destination, file!);
if (task == null) return;
final shot = await task!.whenComplete(() {});
final urlDownload = await shot.ref.getDownloadURL();
print('Download-Link: $urlDownload'); // This prints out the correct url
setState(() {
fileUrl = urlDownload.toString();
});
}
然后我上傳到firebase資料庫:
void postToFirebase(school, String fileName) {
print('fileUrl') ; //But when i check it here it still prints out 'temp'
FirebaseFirestore.instance
.collection("collection_name")
.doc(doc_name)
.collection("collection_name")
.add({
"attachmentUrl": fileUrl,
"attachment_name": fileName,
})
然后我的按鈕(按下時)
onPressed: () async {
uploadFile();
postToFirebase(school, fileName);
}
不知道如何修復。任何幫助將不勝感激,謝謝
uj5u.com熱心網友回復:
該fileUrl欄位uploadFile以異步方式在方法中更新。因此,您不能保證在呼叫以下方法(即postToFirebase.
如果你想讓它按順序作業,你可以使用 promise/future 來調整這個程序。新建一個promise,并在setState回呼中完成它,從而使uploadFile方法回傳一個future,這取決于setState回呼方法中promise的完成。然后 使用future的API將其postToFirebase與前一個鏈接。then
這里的代碼示例:
String fileUrl = "";
Future updateFile() {
Completer completer = Completer();
setState(() {
fileUrl = "new";
completer.complete();
});
return completer.future;
}
void postToFireBase() {
// use the fileUrl updated here
}
void text() {
updateFile().then((value) => postToFireBase());
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/494741.html
上一篇:一個月的細微差別
下一篇:Dart中的建構式Null安全性
