【发布时间】:2021-05-04 07:58:20
【问题描述】:
尝试在 for 循环中获取结果,但 for 循环不等待 firestore 结果。之前也尝试过 forEach。
Future<bool> checkIfNewMessages() async{
bool hasNewMessage=false;
QuerySnapshot _myDoc = await Firestore.instance.collection('PropMap')
.orderBy('ProJoiningDate')
.where('TenId', isEqualTo: globals.memberAuthId)
.getDocuments();
List<DocumentSnapshot> properties = _myDoc.documents;
if(properties.length>0)
for(final property in properties) {
//properties.forEach((property) { //tried forEach() as well
String propid= property.data['PropertyId'];
if(property.data['LastVisitTime']!=null) {
DateTime tenantsLastPropVisitTime = property.data['LastVisitTime'].toDate();
getLastPropertyChatTime(propid).then((latestPropChatTime) { //This 'then' seems not working
print('LAST chat date is ${latestPropChatTime}');
if (latestPropChatTime.isAfter(tenantsLastPropVisitTime)) //This means he has not seen new messages , lets notify him
{
hasNewMessage= true;
}
});
}
};
return hasNewMessage;
}
这些是 fetch 方法,当断点位于 getTheLastChat() 的 getDocuments() 时,控件只是再次跳回 for 循环而不等待结果。
Future getTheLastChat(propId) async {
QuerySnapshot _myDoc =await Firestore.instance.collection('Chats').orderBy('ChatDate', descending: true)
.where('PropertyId', isEqualTo: propId)
.limit(1)
.getDocuments();
List<DocumentSnapshot> tenants = _myDoc.documents;
return tenants;
}
Future<DateTime> getLastPropertyChatTime(propId) async {
DateTime lastChatTime= DateTime.now().add(Duration(days:-365));
var lastChatTimeDocs = await getTheLastChat(propId);
lastChatTime=lastChatTimeDocs.length>0?lastChatTimeDocs[0].data["ChatDate"].toDate():DateTime.now().add(Duration(days:-365));
return lastChatTime;
}
【问题讨论】:
-
你试过传统的
for..loop吗? -
@MuthuThavamani 是的,尝试过,同样的行为,for(var i = 0;i
-
你的
checkIfNewMessages函数是async所以使用await而不是then -
是的,尝试使用
for..loop等待。 -
await with for..in 有效,但我之前尝试过 foreach 等待,知道为什么 foreach 不起作用吗?
标签: flutter dart google-cloud-firestore async-await