简体   繁体   中英

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:

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 ?

Change this print(documentsLoopFromFirestore()); to documentsLoopFromFirestore(); in 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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