Flutter & Firestore: How do I get the most recent first?

Viewed 1151

How do I get the most recent first from Firestore?

FirebaseFirestore.instance.collection(Strings.factsText)
                .where(
                    Strings.category,
                    whereIn: [Strings.climateChange])
                    .orderBy('timestamp', descending: true)
                    .snapshots(),
               
                    ...
                  final factsDocs = snapshot.data.documents;
                  return FactsListContainer(factsDocs: factsDocs);
                });

The issue appears to be with .where when using with .orderBy!

2 Answers

If you have a createdAt field with a timestamp, or an otherwise always incrementing value, you can get the snapshots in descending order of that field with:

stream: FirebaseFirestore.instance
  .collection(Strings.factsText)
  .orderBy('timestamp', descending: true)
  .where(
    Strings.category,
    whereIn: [Strings.climateChange])
    .snapshots(),

Also see the FlutterFire documentation on the Query.orderBy method.

I finally solved it by creating an index in the Firebase console and this worked perfectly so now I'm getting the latest first.

In my database I went to Indexes to create a new index, added my collection name, and then for the fields I added 'category' - descending and 'timestamp' - descending, clicked Collection and then Create Index.

Related