0

I have a stream that fetches data from my Firestore database and orders them according to the latest message. The problem is that the stream does not order them correctly. So basically it fetches the data once, and if I add a new message, it is not shown on top. Any idea why?

Here is my query: The Stream:

 Stream<List<RoomsListModel>>? chats;

The query:

      @override
  void initState() {
    chats = FirebaseFirestore.instance
        .collection("rooms")
        .where("users", arrayContains: userId)
        .where("latestMessage", isNull: false)
        .orderBy("latestMessage")
        .orderBy("latestMessageTime", descending: true)
        .snapshots()
        .asyncMap((events) =>
            Future.wait([for (var event in events.docs) generateRoom(event)]));

    super.initState();
  }
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
cipano
  • 107
  • 1
  • 8
  • 1
    Please edit your question to include how you process the data in a way that shows the problem, e.g. by printing the values that the query is ordered on and that isn't what you expect it to be. – Frank van Puffelen Nov 06 '22 at 14:46
  • 1
    Thank you once again for your help, Frank! Actually, after researching I found a solution to the problem. Added an answer below. – cipano Nov 06 '22 at 19:01

2 Answers2

1

So apparently in Firestore, you cannot do a conditional query like "isNull" and then orderBy another value.

Yes, you can. If a field in Firestore holds the value of null, null being a supported data type, you can query against it. Besides that, you can also order the results by another field, if and only if you create an index.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
0

Found a solution: So apparently in firestore you cannot do a conditional query like "isNull" and then orderBy another value. Therefore I found a workaround: I just changed the conditional query to where "latestMessageTime" is null and ordered by latest Message time.

cipano
  • 107
  • 1
  • 8
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 08 '22 at 20:06