1

I am trying to make a Chat Application in Flutter with Firebase Firestore. I want to show 10 messages with every "Next Load"; while updating the stream with all new incoming messages. (I want to perform this action with the least amount of reads possible because, otherwise, my app would be quite costly to me!).

I have gone through almost every single one of the articles and videos about it. However, they don't really help a lot: 1 because they are relatively outdated, and 2 because I am an amateur Flutter/Firebase Developer.

...

late Stream<QuerySnapshot> _messagesStream;

@override
void initState() {
  super.initState();

  // ----------- Messages Stream --------------- // 
  _messagesStream = ref.doc(widget.chatID)
  .collection("Messages")
  .limit(10)
  .orderBy("sentDate", descending: true)
  .snapshots();

}

...

@override
Widget build(BuildContext context) {

  ...

  StreamBuilder<QuerySnapshot>(
    stream: _messagesStream,
    builder: (context, snapshot) {
      if(snapshot.hasData == true) {
        // ------- Messages Data from Firestore ------------ //
        var messages = snapshot.data!.docs;

        // ------- Message List ------------ //
        List<HangoutMessageModel> _messageList = [];

        for(var message in messages) {
         // ------- Message Model ------------ //
         HangoutMessageModel _messageModel = HangoutMessageModel(
           message["message"]
           message["sentDate"],
           message["senderID"],
           message["messageID"],
         ),

         // ------- Adding message to List ------------ //
         _messageList.add(_messageModel);

         // ------- Sorting newest at the bottom ------------ //
         _messageList.sort((a, b) => (b.sentDate).compareTo(a.sentDate));

        }

        // ------------- Displaying Message List ------------- //
        return ListView.builder(
          itemCount: _messageList.length,
          reverse: true,
          itemBuilder: (context, index) {
            return Container(
              child: Text("${_messageList[index].message}"),
            );
          }
        );
      }
    }
  ),

  ... 

}


Please Help me I spent like almost a week on this thing, but haven't gotten anywhere yet.

Thanks in advance,

1
  • Does anyone have any answer?
    – Uraam Asif
    Commented May 24, 2023 at 6:36

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.