0

i have implemented this code for retrieving the messages of this room.

final messagesProvider = StreamProvider((ref) {
  FirebaseFirestore db = FirebaseFirestore.instance;
var room = ref.watch(roomIdProvider);
  print('room updated');
  print('room is '+room);
  final docRef = db
.collection("messages")

.where("chat_room_id",isEqualTo: room)
    // .orderBy('created_at')
    // .orderBy('created_at',descending: true)



;
print(docRef.orderBy("created_at").snapshots());

  return docRef.snapshots();
});

i want to sort the data and have tried these two lines separately but not worked for me

     .orderBy('created_at')
     .orderBy('created_at',descending: true)

where created at is a timestamp field.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Here, there are some examples about this ([order by not returning](https://stackoverflow.com/questions/51434167/firestore-query-orderby-not-working) and [firestore order by](https://github.com/flutter/flutter/issues/15928)) and in all of them it is recommended to use the index. You can follow the [instructions here](https://github.com/flutter/flutter/issues/15928#issuecomment-619352394) to do it. – Sandeep Vokkareni Jun 10 '22 at 10:08

1 Answers1

0

I added a new collection called "school", there're two items added inside the document.

I used my code, and it works. Could you please remove ".where" and try it again?

  void getMessagesTest() async{
    QuerySnapshot querySnapshot = await _firestore.collection('school').orderBy('age',descending: true).get();
    final allData = querySnapshot.docs.map((doc) => doc.data()).toList();
    print(allData);
  }

enter image description here enter image description here enter image description here

Updated 20220616: enter image description here

Updated 20220618: Yes, you could chain where and orderBy together. Please see my code below. Reference link => Using Where and Order by different fields in Firestore query

  void getMessagesTest() async{
    QuerySnapshot querySnapshot = await _firestore.collection('school').orderBy('age', descending: true).where('age', isGreaterThan: 17).get();
    final allData = querySnapshot.docs.map((doc) => doc.data()).toList();
    print(allData);
  }

enter image description here

Frederic Chang
  • 509
  • 1
  • 5
  • 13