Home > OS >  Why sometime reading document from Firestore not in order in flutter?
Why sometime reading document from Firestore not in order in flutter?

Time:04-13

I Got all documents from collection by below codes

FirebaseFirestore.instance.collection(AppString.FB_POSTS).orderBy('ts',descending: true).limit(10).get().then((querySnapshot){
      querySnapshot.docs.asMap().forEach((index,document)  {
        FirebaseFirestore.instance.collection(AppString.FB_POSTS).doc(document.id).get().then((dataSnapshot){
          print(index);
        });
      }
      );
    });

This codes works perfectly yesterday, but today what i saw froWhich loop not working in order.

Output:

flutter: 8
flutter: 7
flutter: 4
flutter: 3
flutter: 2
flutter: 5
flutter: 1
flutter: 6
flutter: 0
flutter: 9 

Expected Output:

flutter: 0
flutter: 1
flutter: 2
flutter: 3
flutter: 4
flutter: 5
flutter: 6
flutter: 7
flutter: 8
flutter: 9

enter image description here

CodePudding user response:

Your code is asynchronous. That means, you are never guaranteed, that the order will stay the same.

What's happening is: For every entry in your document snapshots list (by running forEach) an asynchronous function (get) is called. Those will finish "at any time", meaning that the first element might finish last, thus resulting in your print for that getting run last.

Also, when using "get" on a collection or query, you already receive the documents. There is no need to fetch them again :)

  • Related