realtime database fireabase get reverse data

I’m creating a chat app in flutter using firebase realtime database.

But I want to get reverse data to set the chat.
can any one help me with this?

var fireDatabase3 = FirebaseDatabase.instance.ref("messages");
    
FirebaseAnimatedList(
   query: fireDatabase3,
    reverse: true,
    itemBuilder: (context, snapshot, animation, index) {

      if (snapshot.child("chatID").value == chatMainScreenProvider.userDetails["chatID"]) {
        if (snapshot.child("senderID").value.toString() == sharedPreferenceProvider.userId.toString()) {
          return _chatBubble(
            snapshot.child("message").value.toString(),true);
        } else {
          return _chatBubble(
            snapshot.child("message").value.toString(),false);
        }
      }else{
        return SizedBox.shrink();
      }
    },
  )

Database Image

>Solution :

The Firebase Realtime Database can only return children in ascending order. It has no option to return them in descending order.

The two most common workarounds to get the results in descending order are:

  1. Reorder the results client-side.
  2. Insert an inverted value into the database, and order on that.

In your screenshots I see a dateTime property that looks like an inverted timestamp. That makes it seem that you’re trying to use option #2, except for the fact that you’re storing the value as a string instead of a number.

You can already try:

query: fireDatabase3.orderByChild("dateTime"),

That should work as the timestamp values you have are also lexicographically sortable. But if it doesn’t work (and really: even if it does), you’d do well to change the code that writes this data to store the dateTime as a number instead of a string value.

Also see these closely related questions:

Leave a Reply