我一直在嘗試獲取groupfav存盤在 FireStore 中的值,以將其作為對 a 的參考的一部分傳遞Stream,但即使在initState我獲得相應的值時,原始變數也不會更改為新值,因此它不會加載獲取到的值對應的串列,嘗試了很多解決方案和思路,但無法讓String groupfav更改為新的值。
static String? userID = FirebaseAuth.instance.currentUser?.uid;
static final userColeccion =
FirebaseFirestore.instance.collection("users");
String groupfav = ' '; //this value should be replaced by the future value obtained
late Stream<QuerySnapshot> task;
@override
void initState() {
super.initState();
userColeccion.doc("$userID").get().then((value) {
groupfav = value.data()!["groupfav"];
print(groupfav); //correctly prints the value I want (is "groupid4")
return groupfav;
});
taskGroup = FirebaseFirestore.instance
.collection("groups")
.doc(groupfav) // pass the obtained value
.collection("task")
.snapshots();
}
做這一切應該替換String groupfav = ' ';為String groupfav = 'groupid4',但它不起作用,它停留在'',謝謝!
uj5u.com熱心網友回復:
您正在通過將回呼附加到usersCollection.get()呼叫來進行同步呼叫。只有在.then內部才能實作異步呼叫。此呼叫不會等待,它會一直持續到下一個呼叫,即獲取FirebaseFiresstore.instance ,此時groupfav的值仍然為空。您需要做的是將呼叫嵌套在.then()中,因為在使用.then事件鏈時異步呼叫如何作業,然后(雙關語!)將設定該值,所以這樣做這:
userColeccion.doc("$userID").get().then((value) {
groupfav = value.data()!["groupfav"];
print(groupfav); //correctly prints the value I want (is "groupid4")
// right inside the **.then, after getting the value
// THEN you can fetch the document with name 'groupfav'
// from your collection
taskGroup = FirebaseFirestore.instance
.collection("groups")
.doc(groupfav) // pass the obtained value
.collection("task")
.snapshots();
});
不幸的是,您不能使initState異步(用async關鍵字裝飾它),否則我會建議使用await而不是.then。另一種方法是將所有這些操作放入一個單獨的方法中,該方法確實等待對usersCollection的呼叫,如:
@override
void initState() {
super.initState();
getGroupFavData();
}
void getGroupFavData() async {
var groupFavData = await userColeccion.doc("$userID").get();
var groupfav = groupFavData.data()!['groupfav'];
taskGroup = FirebaseFirestore.instance
.collection("groups")
.doc(groupfav) // pass the obtained value
.collection("task")
.snapshots();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/439615.html
