【问题标题】:wait for firestore documents in for loop在 for 循环中等待 firestore 文档
【发布时间】: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


【解决方案1】:

您可以使用 Future.forEach 来满足您的要求

  Future<void> buildData(AsyncSnapshot snapshot) async {
    await Future.forEach(snapshot.data.documents, (element) {
      employees.add(Employee.fromSnapshot(element));
    });
  }

【讨论】:

    猜你喜欢
    • 2023-01-20
    • 2018-06-09
    • 2018-01-06
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多