'Flutter Firebase documents are randomly ordered

I made a simple chat app using Flutter. My app is functioning perfectly fine (getting and dumping data into firebase) but once my messages get into my database, they are randomly ordered resulting in my msgs getting displayed in a random order.

I have tried reversing the SnapshotQueue in my Flutter code but that did not help...



Solution 1:[1]

You will need to attach document names to your documents before uploading them. I think you are experiencing this issue because your documents are being given Auto Ids.

Try using the current timestamp as the document name. this will help arrange documents in order according to time uploaded.

Firestore.instance.collection(CollectionName).document(Timestamp.now()).setData(messageMap);

i hope this is what you need. if not. Please share your code that uploads the message to database.

Solution 2:[2]

  1. Add a field like datePublished = DateTime.now() to each message document as it gets created to store the timestamp of when the message was created

  2. Then you can use datePublished field to order your documents of your QuerySnapshot like this:

    QuerySnapshot snapshot = await collection.orderBy('datePublished', descending: true).get();

    now your messages are arranged in chronological order from the latest to earliest.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tonny Baw
Solution 2