0
votes

I'm trying to create chat demo app with firebase in flutter but when i send message, then those message documents are being created at randomly any places in firestore database. thats why my chat screen messages are in wrong manner, means not arranged according to time.

Some piece of code:

method for saving message details to firestore:

Future<void> sendMesssage() async{
   if(messagesController.text.length>0){
     String msgId = firestore.collection("messages").document().documentID.toString();

     await firestore.collection("messages").document(msgId).setData({
       'text': messagesController.text,
       "from": widget.user.user.email, //sender email Id
       "to":widget.chatMateEmail, // receiver email id
       "msgId":msgId,
       "senderUid": widget.user.user.uid, //sender uid
       "receiverUid":widget.receiverUid //receiver uid
     });
     messagesController.clear();

   }
  }

UI For chat screen:

method for fetching messages from firestore:

Expanded(
  child: StreamBuilder<QuerySnapshot>(
    stream: firestore.collection("messages").snapshots(),
    builder: (context, snapshot){
      if(snapshot.hasError){
          return Center(child: Text("${snapshot.error}"),);
        }
      if(!snapshot.hasData){
          return Center(child: CircularProgressIndicator(),);
        }else{
               List<DocumentSnapshot> docs = snapshot.data.documents;
                return
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: ListView.builder(
                    itemCount: docs.length,
                    itemBuilder: (context, index){
                        print("Messagessssssss:${docs[index]['text']}");
                        return Message( // custom class
                          from:  docs[index]['from'],
                          text: docs[index]['text'],
                          me: widget.user.user.email == docs[index]['from'],
                        );

                      },
                     ),
                   );
                  }
                },
              ),
            ),

chat Screen:

enter image description here

My Cloud Firestore Screenshot:

enter image description here

1
Firestore doesn't sort documents chronologically by default. You will need to add a timestamp field your documents, and order your query by that field.Doug Stevenson
@DougStevenson Sir, timestamp means DateTime..! Would you please add your comment in code form?Shruti Ramnandan Sharma
Thank you so much sir, It got solved according to your suggestion :)Shruti Ramnandan Sharma

1 Answers

1
votes

It got solved according to @DougStevenson sir's answer, I added new field with name "messageTime" and add DateTime.now(), And fetched messages according to messageTime (sort by ascending order ).

I modified a little bit my code & working perfectly:

 Future<void> sendMesssage() async{
   if(messagesController.text.length>0){
     String msgId = firestore.collection("messages").document().documentID.toString();

     await firestore.collection("messages").document(msgId).setData({
       ..........
       "messageTime": DateTime.now() // message DateTime
     });
     messagesController.clear();

   }
  }
Expanded(
  child: StreamBuilder<QuerySnapshot>(
    stream: firestore.collection("messages").orderBy('messageTime', descending: false).snapshots(), //and sort by ascending order according to datetime.
    builder: (context, snapshot){
            ......

              },
           ),
         ),