[英]Null value when looping through Firestore documents in a collection in Flutter
I have the following function to loop through the documents and their fields that I have in my Firestore collection and display them as a map in the console:我有以下 function 来循环浏览我在 Firestore 集合中拥有的文档及其字段,并在控制台中将它们显示为 map:
documentsLoopFromFirestore() {
FirebaseFirestore.instance
.collection('myCollection')
.get()
.then((idkWhatGoesHereButICantRemoveIt) {
idkWhatGoesHereButICantRemoveIt.docs.forEach((result) {
print(result.data());
});
});
}
When I call documentsLoopFromFirestore()
in a button with:当我在按钮中调用documentsLoopFromFirestore()
时:
ElevatedButton(
onPressed: () {
print(documentsLoopFromFirestore());
},
I get the following result in the console:我在控制台中得到以下结果:
I/flutter (29803): null
I/flutter (29803): {lastName: smith, name: peter}
I/flutter (29803): {lastName: doe, name: john}
It successfully prints the values of my documents in that Firestore collection, but just before it does so, it throws that null
that is not allowing my to add this map to another collection which is my objective.它成功地在该 Firestore 集合中打印了我的文档的值,但在此之前,它会抛出不允许我将此null
添加到另一个集合中的 null,这是我的目标。
If I add async
and await
to the function:如果我将async
和await
添加到 function:
documentsLoopFromFirestore() async {
await FirebaseFirestore.instance
.collection('myCollection')
.get()
.then((idkWhatGoesHereButICantRemoveIt) {
idkWhatGoesHereButICantRemoveIt.docs.forEach((result) {
print(result.data());
});
});
}
Then I get:然后我得到:
I/flutter (29803): Instance of 'Future<dynamic>'
I/flutter (29803): {lastName: smith, name: peter}
I/flutter (29803): {lastName: doe, name: john}
It seems like it throws the null
when doing the first loop.似乎在执行第一个循环时会抛出null
。 Does anyone knows how I can get rid of this null
?有谁知道我怎样才能摆脱这个null
?
Change this print(documentsLoopFromFirestore());更改此打印(documentsLoopFromFirestore()); to documentsLoopFromFirestore();到文档LoopFromFirestore(); in ElevatedButton在 ElevatedButton 中
The reason you see a null
with the first code and the Instance od Future<dynamic>
is that you first print out your function and the the result.您看到带有第一个代码和Instance od Future<dynamic>
的null
的原因是您首先打印出 function 和结果。
In the first case the function soend't return anything so you see null
and in the second the function is a Furture to you just print that it is a future.在第一种情况下,function 不会返回任何内容,因此您会看到null
,在第二种情况下,function 是未来,您只需打印它就是未来。
To awoid that either remove the first print or return the values in the format you want in the function.为了避免删除第一个打印或以 function 中所需格式返回值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.