Reputation: 37
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:
documentsLoopFromFirestore() {
FirebaseFirestore.instance
.collection('myCollection')
.get()
.then((idkWhatGoesHereButICantRemoveIt) {
idkWhatGoesHereButICantRemoveIt.docs.forEach((result) {
print(result.data());
});
});
}
When I call documentsLoopFromFirestore()
in a button with:
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.
If I add async
and await
to the 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.
Does anyone knows how I can get rid of this null
?
Upvotes: 0
Views: 39
Reputation: 7398
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.
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.
To awoid that either remove the first print or return the values in the format you want in the function.
Upvotes: 0
Reputation: 287
Change this print(documentsLoopFromFirestore()); to documentsLoopFromFirestore(); in ElevatedButton
Upvotes: 1