【问题标题】:How to fetch data from firestore documents from a collection and store in the list如何从集合中的firestore文档中获取数据并存储在列表中
【发布时间】:2020-09-24 20:13:41
【问题描述】:

我有一个文档 ID 列表,我想从 Firestore 获取这些文档的数据并使用 FutureBuilder 显示它。

contestList = [awebnmsdfjkeeer23,324cdas4asdf, 34sdfasgadsg]
Future<void> fetchUsergameData() async {

    contestList.forEach((element) async{ 
        await Firestore.instance.collection('LiveGames').document('$element')
            .get().then((dss) {
                if(dss.exists) {
                    tempgame.add(dss.data["GameData"]);
                    temproom.add(dss.data["Room"]);
                    temptitle.add(dss.data["Title"]);
                    temp = tempgame + temproom + temptitle;
                    joinedContests.add(temp);
                }
            }).then((value) => {});
        });

        print(joinedContests);

    }
}

我已经使用上面的函数来获取数据并尝试存储在列表中,就像列表中的一个文档数据一样。但我得到了数据的空白列表。如何在flutter中使用FutureBuilder获取整个文档并显示出来

【问题讨论】:

  • 我对第一行很困惑。那些应该是字符串还是变量?无论哪种方式,您都不需要'$element',只需element。也许这就是您没有收到文档的原因(错误/未指定的 id)。

标签: firebase flutter dart google-cloud-firestore


【解决方案1】:

您的代码似乎有多个不同的问题:

  • contestList 的关键字无效。 324cdas4asdf34sdfasgadsg 不是有效的变量名,因为它们都以数字开头,这不是有效的变量名。如果它们应该是您要检索的 id,则它们必须用 " 括起来,这将使它们成为字符串。
  • 您正在尝试使用'$element' 访问文档,就好像它是一个bash 变量一样,但是那里有两个问题:它不是那样做的,也没有必要这样做。 element 已经将值保存为字符串,因此只需按原样访问即可。
  • 您调用了方法then 两次,第二次没有做任何事情。这不应该是一个问题,但它根本没有做任何事情,我可以省略。

您将在下面看到修复所有上述错误的代码的编辑版本。

contestList = ["awebnmsdfjkeeer23", "324cdas4asdf", "34sdfasgadsg"]
Future<void> fetchUsergameData() async {

    contestList.forEach((element) async{ 
        await Firestore.instance.collection('LiveGames').document(element)
            .get().then((dss) {
                if(dss.exists) {
                    tempgame.add(dss.data["GameData"]);
                    temproom.add(dss.data["Room"]);
                    temptitle.add(dss.data["Title"]);
                    temp = tempgame + temproom + temptitle;
                    joinedContests.add(temp);
                }
            });
        });

        print(joinedContests);

    }
}

另一方面,我们不知道 tempgametemproomtemptitle 的类型,但从您访问它的方式来看,您可能只想做这样的事情:

tempgame = dss.data["GameData"];
temproom = dss.data["Room"];
temptitle = dss.data["Title"];
temp = tempgame + temproom + temptitle;
joinedContests.add(temp);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-06
    • 2021-09-28
    • 2020-09-05
    • 1970-01-01
    • 2022-10-12
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    相关资源
    最近更新 更多