Home > Net >  Firestore Query not ordering data correctly
Firestore Query not ordering data correctly

Time:11-07

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();
  }

CodePudding user response:

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.

CodePudding user response:

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.

  • Related