繁体   English   中英

循环通过 Flutter 中集合中的 Firestore 文档时的 Null 值

[英]Null value when looping through Firestore documents in a collection in Flutter

我有以下 function 来循环浏览我在 Firestore 集合中拥有的文档及其字段,并在控制台中将它们显示为 map:

documentsLoopFromFirestore() {
    FirebaseFirestore.instance
      .collection('myCollection')
      .get()
      .then((idkWhatGoesHereButICantRemoveIt) {
        idkWhatGoesHereButICantRemoveIt.docs.forEach((result) {
      print(result.data());
    });
  });
}

当我在按钮中调用documentsLoopFromFirestore()时:

ElevatedButton(
 onPressed: () {
   print(documentsLoopFromFirestore());
 }, 

我在控制台中得到以下结果:

I/flutter (29803): null
I/flutter (29803): {lastName: smith, name: peter}
I/flutter (29803): {lastName: doe, name: john}

它成功地在该 Firestore 集合中打印了我的文档的值,但在此之前,它会抛出不允许我将此null添加到另一个集合中的 null,这是我的目标。

如果我将asyncawait添加到 function:

documentsLoopFromFirestore() async {
    await FirebaseFirestore.instance
      .collection('myCollection')
      .get()
      .then((idkWhatGoesHereButICantRemoveIt) {
        idkWhatGoesHereButICantRemoveIt.docs.forEach((result) {
      print(result.data());
    });
  });
}

然后我得到:

I/flutter (29803): Instance of 'Future<dynamic>'
I/flutter (29803): {lastName: smith, name: peter}
I/flutter (29803): {lastName: doe, name: john}

似乎在执行第一个循环时会抛出null 有谁知道我怎样才能摆脱这个null

更改此打印(documentsLoopFromFirestore()); 到文档LoopFromFirestore(); 在 ElevatedButton 中

您看到带有第一个代码和Instance od Future<dynamic>null的原因是您首先打印出 function 和结果。

在第一种情况下,function 不会返回任何内容,因此您会看到null ,在第二种情况下,function 是未来,您只需打印它就是未来。

为了避免删除第一个打印或以 function 中所需格式返回值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM