我有這個函式,當我按下上傳按鈕時會呼叫它。它應該在 Firestore 中創建一個名為userPosts的集合,其中包含postId、ownerId和mediaUrl。除了用戶名之外,一切正常,因為我必須從 Firestore 中另一個名為users的集合中獲取它。所以我有這個錯誤:未處理的例外: 無效的引數:'Future <String>'的實體我該如何解決這個問題?謝謝!
final userRef = FirebaseFirestore.instance.collection('users');
final postsRef = FirebaseFirestore.instance.collection('posts');
createPostInFirestore({required String mediaUrl}) {
postsRef.doc(user!.uid).collection("userPosts").doc(postId).set({
"postId": postId,
"ownerId": user!.uid,
"username": userRef.doc(user!.uid).get().then((snapshot) {
return snapshot.data()!['username'].toString();
}),
"mediaUrl": mediaUrl,
"timestamp": timestamp,
"likes": {},
});
}
uj5u.com熱心網友回復:
和 方法是異步的get()(set()需要時間來決議),所以我們需要用async關鍵字使函式異步,然后等待獲取用戶名,然后等待更新資料set()。嘗試這個:
final userRef = FirebaseFirestore.instance.collection('users');
final postsRef = FirebaseFirestore.instance.collection('posts');
Future<void> createPostInFirestore({required String mediaUrl}) async {
final username = await userRef.doc(user!.uid).get().then((snapshot) {
return (snapshot.data() as Map<String, dynamic>)!['username'].toString();
});
await postsRef.doc(user!.uid).collection("userPosts").doc(postId).set({
"postId": postId,
"ownerId": user!.uid,
"username": username,
"mediaUrl": mediaUrl,
"timestamp": timestamp,
"likes": {},
});
}
然后在onPressedor 將執行此功能的方法上,您還需要像這樣等待它:
onPressed: () async {
await createPostInFirestore("your string URL here");
}
現在它會正常作業
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/532407.html
標籤:Google Cloud Collective 扑火力基地镖谷歌云火库
