通过单个功能获取多个文档

时间:2019-07-11 13:38:20

标签: flutter dart google-cloud-firestore

我有一个函数,该函数接受ID列表,并应该获取具有这些ID的所有文档,然后返回List<Map<String, dynamic>>。我遇到的第一个问题是Firestore for flutter无法在单个网络调用中从集合中获取多个文档。 (我在这里想念东西吗? )

因此,我在ID列表上运行了一个forEach循环,并将获得的数据添加到一个空列表中,如下所示:

interestIds.forEarch((id) {
  _db.collection('interests').document(id).get().then((DocumentSnapshot snap) {
    result.add(snap.data);
   }
 });
return result;

您可能已经猜到这并没有真正起作用,因为return语句在获取所有文档之前就已执行。我该如何解决这个问题?

更新后的代码,如注释中所述:

  Future<List<Map<String, dynamic>>> getAllInterestsOfUser(
      List<String> interestIds) async {
    //Returns list of all intrests objects given a list of interestIds
    List<Map<String, dynamic>> result = List();

    await interestIds.forEach((id) {
      _db
          .collection('interests')
          .document(id)
          .get()
          .then((DocumentSnapshot snap) {
        print('Fetched: ' + snap.data.toString());
        result.add(snap.data);
      });
    });
    print('Interests: ' + result.toString());
    return result;
  }

应用程序输出:

I/flutter (12578): Interests: []
I/flutter (12578): Function Call: []
I/flutter (12578): Fetched: {conversationId: -LjS54Q0c7wcQqdwePT6, 49wotilxfSRbADygh7kt3TSscnz1: {//moredata}

0 个答案:

没有答案
相关问题