2

I've created an app and I am using firebase as well but I want to order the documents by timestamp such that my documents will be ordered from recently added ones to older ones.

I wonder if there is a solution rather than using orderBy method because my project is very big.

please help me.

Note: I am devolping the app using flutter & dart.

dfdfdsfsd
  • 327
  • 1
  • 5
  • 14

1 Answers1

3

Firebase Realtime Database always returns results in ascending order. There is no way to order descending order.

This means you have two common options:

  1. Reverse the nodes on the client.
  2. Store an inverted value in a property, and order on that.

If you want to retrieve a subset of the items, keep in mind that you can combine any of these approaches with limitToFirst() and limitToLast. For example, to get the 10 most recent messages, you could:

  1. order on timestamp
  2. get the last 10 items
  3. reverse them client-side

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • I did as you have mentioned above and I've created a field called time and it is equal to DateTime.now() (Dart) but it orders according to the current time of the users so this makes a disturbance in my app especially in chats – dfdfdsfsd Dec 17 '19 at 11:16
  • That sounds like a new problem problem to me. But if you want to have a consistent timestamp that is not dependent on the client-side click, use [`ServerValue.timestamp`](https://pub.dev/documentation/firebase_database/latest/firebase_database/ServerValue/timestamp-constant.html). Read more about it in the documentation here: https://firebase.google.com/docs/database/android/offline-capabilities#server-timestamps – Frank van Puffelen Dec 17 '19 at 14:52