Reputation: 33
I have an async method to return the length of the documents of a firebase query with condition and o have implemented with await in the method. The code is below.
////////////////////////
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
Here if you notice, it always executes the OUTSIDE METHOD line first hence always get with value as 0
I need to get the value from the method getUreadMsgCount initialized first then proceed with the next line. Any helps?
Upvotes: 0
Views: 763
Reputation: 80914
You need to use await
:
var result = await getUreadMsgCount(groupChatId, id);
unReadCount = result;
print("COUNT WITHIN getUreadMsgCount Method : $unReadCount");
print("UNREAD OUTSIDE METHOD : $unReadCount");
This way the code, after the asynchronous method call will get executed after retrieving the data.
The reason this:
getUreadMsgCount(groupChatId, id).then((result) {
unReadCount = result;
print("COUNT WITHIN getUreadMsgCount Method : $unReadCount");
});
print("UNREAD OUTSIDE METHOD : $unReadCount");
is not printing as you want, is because the method getUreadMsgCount
is asynchronous, then the code after the then()
method will be executed first and when the data is fully retrieved, the code inside the then()
method will get executed.
https://dart.dev/codelabs/async-await#execution-flow-with-async-and-await
Upvotes: 1