我試圖在我的函式中獲取回傳值,但輸出是“未來實體”而不是資料庫中學校欄位名稱的值
@override
void initState() {
userId = _auth.currentUser!.uid;
publisherSchool =
getName(widget.postInfo['publisher-Id'], 'school').toString();
super.initState();
}
Future getName(String publisherUid, String fieldname) async {
DocumentSnapshot publisherSnapshot = await FirebaseFirestore.instance
.collection('users')
.doc(publisherUid)
.get();
print(publisherSnapshot.get(fieldname));
return publisherSnapshot.get(fieldname);
}
但是每當我列印publisherSnapshop.get(fieldname) 時,我都會從資料庫中獲取正確的值
uj5u.com熱心網友回復:
宣告getName()函式時,指定回傳型別為Future<String>,然后呼叫時getName()需要等待結果 egpublisherSchool = await getName(widget.postInfo['publisher-Id'], 'school').toString();
uj5u.com熱心網友回復:
有兩種方法可以做到,您可以創建一個Future方法并在initState下面呼叫它:
@override
void initState() {
initial();
super.initState();
}
Future<void> initial() async {
userId = _auth.currentUser!.uid;
// Remember using `()` to wrap the `await` to get it result
publisherSchool = (await getName(widget.postInfo['publisher-Id'], 'school')).toString();
}
或者您可以使用.then直接在 內呼叫它initState:
@override
void initState() {
userId = _auth.currentUser!.uid;
getName(widget.postInfo['publisher-Id'], 'school').then((value) {
publisherSchool = value.toString();
});
super.initState();
}
uj5u.com熱心網友回復:
您沒有得到正確回應的原因是,無論何時使用 Futures 都需要一些時間來完成并回傳結果。同時,它正在獲取您必須讓它等待的結果,以便程式將在未來功能完成后繼續運行,因為 await/then 在您的代碼中無處可尋,因此存在問題。
要解決此問題,請進行以下更改:
改變
publisherSchool =
getName(widget.postInfo['publisher-Id'], 'school').toString();
到
getName(widget.postInfo['publisher-Id'],
'school').then((value){
publisherSchool=value.toString()});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/334729.html
標籤:扑
