我有一个异步方法来返回带条件的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

08-18 22:58
查看更多