Rusben Wladiskoz
Rusben Wladiskoz

Reputation: 563

How to order data from Firestore in Flutter, orderBy not ordering correct

I'm building an app where the users can write into my db and ask questions to other users, like a doctor app. Where the doctors can answer the questions.

I wanna order the questions by date, where I would like to order the questions by newest, and also the most popular.

I try to order the newest by the following:

date: "29 September 2019"

Firestore.instance
        .collection("Questions")
        .orderBy("date", descending: true) // 1 will be last, 31 will be latest
        .snapshots(),

But that seem not to work. So I wonder how I could order the data correctly from my query from firebase. Or do I have to store the date as a long in the firebase and then convert it maybe?

Also, I would like to order the most popular questions, based on how many users have watched that particular questions by:

questionsView: "3", questionsView: "1032" etc

Firestore.instance
        .collection("Questions")
        .orderBy("questionsView")
        .snapshots(),

But neither does this do the ordering correctly.

I saw a great post from the legendery Frank von Puffen but I didn't really understand that, so I wonder if somebody could help me out on this.

Here's his post: Ordering Data In FireStore

Best regards, Rusben

Upvotes: 6

Views: 7443

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138804

I try to order the newest by the following:

date: "29 September 2019"

But that seem not to work.

It won't work since your date property is of type String. When ordering strings, remember that the strings are ordered lexicographically.

So I wonder how I could order the data correctly from my query from firebase.

To solve this, you should change the type of you property to be a Date. In this case you'll get a chronological order.

Or do I have to store the date as a long in the firebase and then convert it maybe?

That's a solution for ordering elements is for realtime database and not for Cloud Firestore.

I saw a great post from the legendery Frank von Puffen but I didn't really understand that, so I wonder if somebody could help me out on this.

In that case, the station property was holding integers as string values, which in fact is the same thing. In that case, the solution was to change the type of the property to number or to pad the numbers so they all have the same length but in your case, the type of your property should definetely be Date and not a String.

Upvotes: 2

Related Questions