gpt4 book ai didi

firebase - 等待不适用于firebase querySnapshot,执行下一行

转载 作者:行者123 更新时间:2023-12-03 04:57:56 26 4
gpt4 key购买 nike

我有一个异步方法来返回带条件的Firebase查询的文档长度,并且o已在该方法中使用await实现。代码如下。

////////////////////////

getUreadMsgCount(groupChatId, id).then((result) {
unReadCount = result;
print("COUNT WITHIN getUreadMsgCount Method : $unReadCount");
});

print("UNREAD OUTSIDE METHOD : $unReadCount");

////////////////////////////////////////
Future getUreadMsgCount(String groupId, String idFrom) async {
var respectsQuery = Firestore.instance
.collection('messages')
.document(groupId).collection(groupId)
.where('idFrom', isEqualTo: idFrom).where('isSeen', isEqualTo: 0);
var querySnapshot = await respectsQuery.getDocuments();
int totalUnread = querySnapshot.documents.length;
return totalUnread;
}

////////////// OUT PUT ///////////////////////////
I/flutter (28972): UNREAD OUTSIDE METHOD : 0
I/flutter (28972): UNREAD OUTSIDE METHOD : 0
I/flutter (28972): UNREAD OUTSIDE METHOD : 0
I/flutter (28972): COUNT WITHIN getUreadMsgCount Method : 2
I/flutter (28972): COUNT WITHIN getUreadMsgCount Method : 0
I/flutter (28972): COUNT WITHIN getUreadMsgCount Method : 0

在这里,如果您注意到,它总是首先执行OUTSIDE METHOD行,因此总是以0值获得

我需要从首先初始化的getUreadMsgCount方法获取值,然后继续下一行。有帮助吗?

最佳答案

您需要使用await:

var result = await getUreadMsgCount(groupChatId, id);
unReadCount = result;
print("COUNT WITHIN getUreadMsgCount Method : $unReadCount");
print("UNREAD OUTSIDE METHOD : $unReadCount");

这样,异步方法调用之后的代码将在检索数据后执行。

原因如下:
getUreadMsgCount(groupChatId, id).then((result) {
unReadCount = result;
print("COUNT WITHIN getUreadMsgCount Method : $unReadCount");
});

print("UNREAD OUTSIDE METHOD : $unReadCount");


并不是按照您想要的方式打印,是因为方法 getUreadMsgCount是异步的,因此将首先执行 then()方法之后的代码,并在完全检索数据后将执行 then()方法中的代码。

https://dart.dev/codelabs/async-await#execution-flow-with-async-and-await

关于firebase - 等待不适用于firebase querySnapshot,执行下一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60240958/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com