I add some data to the collection. When i retrive it, it is sorted by that generated id. Is it posible to make firebase to sort it in chronological order or it is required to add one more field with date and sort it once it is retrived in flutter?
Asked
Active
Viewed 1.3k times
9
-
why not use orderBy in the query? – Logemann Oct 05 '19 at 16:46
3 Answers
20
Yes you need a createdAt
timestamp field and use it like
Firestore.instance
.collection("users")
.orderBy('createdAt', descending: true or false).getDocuments()
And you can store createdAt
on flutter side with Timestamp
(Its included in cloud_firestore
), and you can get current timestamp with Timestamp.now()

ibrahimkarahan
- 2,697
- 1
- 9
- 20
-
getting error in console: "Status{code=FAILED_PRECONDITION, description=The query requires an index. You can create it here...." any suggestion, thanks. – Kamlesh Jun 16 '21 at 06:33
-
You should create index by following the link, when we use order feature, firestore needs to create index for performance. – ibrahimkarahan Jun 16 '21 at 10:43
-
Its weird to create index by console url suggested by firebase but I had created index. Thanks. – Kamlesh Jun 16 '21 at 10:46
4
There is no built-in metadata on when a document was inserted. If you want to order the documents by insertion order, you will indeed have to add a field with that information yourself and order on that field when retrieving the documents.

Frank van Puffelen
- 565,676
- 79
- 828
- 807
1
If you have stored ID then you can sort them by id these are generated by firebase using the timestamp.

DARK_C0D3R
- 2,075
- 16
- 21