Ini Hood
Ini Hood

Reputation: 23

flutter List not printing out all data in the list

They are exactly 665 items in my database(firestore) I can query and print all 665 items to the console but when I put them inside a list and print out the list, I am only seeing 60 items. Here is my code

getOnlineUsersContact() async {
  List<String> list = [];
  await FirebaseFirestore.instance
      .collection('userPhones')
      .doc(auth.currentUser!.uid)
      .collection("phoneNumbers")
      .get()
      .then((QuerySnapshot querySnapshot) {
    for (var doc in querySnapshot.docs)  {
      String phoneNumber = doc['number'];
      list.add(phoneNumber);
      print("Mycontact: $phoneNumber"); // prints all 665 items
    }
  });
  print("Mycontact: $list"); // prints only 60 items
}

Have I exceeded the maximum data size limit of the list? What could go wrong?

Upvotes: 0

Views: 672

Answers (1)

Thiago Carvalho
Thiago Carvalho

Reputation: 390

You need to do 2 things:

First, get your querySnapshot:

final querySnapshot = await FirebaseFirestore.instance
      .collection('userPhones')
      .doc(auth.currentUser!.uid)
      .collection("phoneNumbers")
      .get();

Then, you need to work with Future.forEach() to await to iterate through all the items on list

List list = [];

await Future.forEach(querySnapsho.docs, (element) async {
// add to list
});

And, once you await to fill the list, you can print.

It will be like this:

final querySnapshot = await FirebaseFirestore.instance
      .collection('userPhones')
      .doc(auth.currentUser!.uid)
      .collection("phoneNumbers")
      .get();
    
List list = [];

await Future.forEach(querySnapsho.docs, (element) async {
// add to list
});

print(list);

It is occurring because you aren't waiting for the inside then() callback. All inside then() will be completed in some time in the future that you aren't waiting for.

Upvotes: 1

Related Questions