Streambuilder is not showing chat messages from collection

  1. Summary of my problem
    Flutter Streambuilder is not showing chat messages from dynamically passed collection name. Collection name is fetched from firebase before the build widget.
  • Details about my goal
    I am fetching the string data i.e “lastCollection” stored in a document, and trying to generate new collection (if ‘lastCollection’ not generated before) whenever message screen is opened, and passing that new collection name to streambuilder to stream chat messages on screen.

  • Expected Results
    Whenever i open chat screen it should show the messages from collection name passed and stream chats messages sent at that time also.

  • Actual Results
    It is showing blank screen without any chat message.

  • Error Messages (if any)
    These are the errors i see in debug console, please refer: https://prnt.sc/109fzpi

  1. What have I tried so far -
  • Put my code in initState and get latest collection name from firebase and then call streamBuilder.
  • Wrapped streambuilder inside futureBuilder and passed the collection name after getting Collection data from futureBuilder.
  • Have put my code inside the build widget and then passed the “lastCollection” value to streamBuilder in return.
  1. Here’s the minimum code you would need to reproduce the problem -
    To format your code enter between 3 backticks like this
  • Connect flutter with firebase

  • Create a chat collection, inside the document add field String “lastCollection”, then create new collection dynamically through code and addthat collection name to “lastCollection” field.

  • Add document fields inside dynamic created collection, as String “text”.

  • Pass that dynamic collection name to streambuilder and show text mesages.

Please refer my code:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:bubble/bubble.dart';
import 'package:intl/intl.dart';

class ChatMessage extends StatefulWidget {
  ChatMessage(this.userId, this.advisorId, this.convoId, this.chatStatus);
  final String userId;
  final String advisorId;
  final String convoId;
  final bool chatStatus;
  String collectionName;

  @override
  _ChatMessageState createState() => _ChatMessageState();
}

class _ChatMessageState extends State<ChatMessage> {
  @override
  Widget build(BuildContext context) {
    String lastCollectionName;
    bool endChat = true;
    lastCollectionName = DateTime.now().millisecondsSinceEpoch.toString();

    DocumentReference convoDoc =
        Firestore.instance.collection('chats').document(widget.convoId);

    // get info about last chat
    convoDoc.get().then((value) async {
      if (value.data != null) {
        endChat = value.data['endChat'];
        // if endchat is false, chat thread is active, we surely have last active collection name
        if (!endChat) lastCollectionName = value.data['lastCollectionName'];
      }
      DocumentReference messageDoc;

      if (endChat) {
        // if endchat true, no active chat thread, need to create new with timestamp
        messageDoc =
            convoDoc.collection(lastCollectionName).document('chatStats');
        await messageDoc.setData(<String, dynamic>{
          'startTime': '',
        });
        // update new collection name to main chat reference document
        await convoDoc.setData(
          <String, dynamic>{
            'users': <String>[
              widget.userId,
              widget.advisorId,
            ],
            'lastCollectionName': lastCollectionName,
            'endChat': false,
            'startTimeStored': '',
          },
        );
      }
      widget.collectionName = lastCollectionName;
    });
    if (widget.collectionName != null)
      return Flexible(
        child: StreamBuilder(
          stream: Firestore.instance
              .collection('chats')
              .document(widget.convoId)
              .collection(widget.collectionName)
              .snapshots(),
          builder:
              (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(
                child: CircularProgressIndicator(),
              );
            }
            print(widget.collectionName);
            if (snapshot.hasData || snapshot.hasData != null) {
              return ListView.builder(
                padding: const EdgeInsets.all(10.0),
                itemBuilder: (BuildContext context, int index) =>
                    buildItem(index, snapshot.data.documents[index], context),
                itemCount: snapshot.data.documents.length,
                reverse: true,
              );
            } else {
              return Container();
            }
          },
        ),
      );
    return Container();
  }

  Widget buildItem(int index, DocumentSnapshot document, context) {
    // if (!document['read'] && document['idTo'] == widget.userId) {
    //   print('updateMessageRead');
    //   // Database.updateMessageRead(document, convoId);
    // }

    if (document.documentID != 'chatStats') {
      final messageDateFormat = new DateFormat('hh:mm');
      String _type = document['type'];

      if (document['idFrom'] == widget.userId) {
        // Right (my message)
        return Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: <Widget>[
            Container(
              padding: EdgeInsets.only(
                right: 10.0,
              ),
              child: Text(
                messageDateFormat.format(
                  new DateTime.fromMillisecondsSinceEpoch(
                    int.parse(
                      document['timestamp'],
                    ),
                  ),
                ),
                style: TextStyle(
                  fontSize: 14,
                ),
              ),
            ),
            Container(
              margin: EdgeInsets.symmetric(vertical: 5),
              child: Bubble(
                color:
                    (_type == 'image') ? null : Theme.of(context).primaryColor,
                elevation: 0,
                padding: const BubbleEdges.all(10.0),
                nip: BubbleNip.rightBottom,
                child: _type == 'image'
                    ? Image.network(
                        document['content'],
                        height: 150,
                      )
                    : Text(
                        document['content'],
                        style: TextStyle(
                          color: Colors.white,
                        ),
                      ),
              ),
              width: 200,
            ),
            SizedBox(
              height: 10,
            ),
          ],
          // mainAxisAlignment: MainAxisAlignment.end,
        );
      } else {
        // Left (peer message)
        return Container(
          margin: EdgeInsets.symmetric(vertical: 5),
          child: Column(
            children: <Widget>[
              Row(
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.only(
                      right: 10.0,
                    ),
                    child: Text(
                      messageDateFormat.format(
                        new DateTime.fromMillisecondsSinceEpoch(
                          int.parse(
                            document['timestamp'],
                          ),
                        ),
                      ),
                      style: TextStyle(
                        fontSize: 14,
                      ),
                    ),
                  ),
                  Container(
                    child: Bubble(
                      color: Colors.white10,
                      elevation: 0,
                      padding: const BubbleEdges.all(10.0),
                      nip: BubbleNip.leftTop,
                      child: Text(
                        document['content'],
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                    width: 200.0,
                    margin: const EdgeInsets.only(left: 10.0),
                  ),
                ],
              ),
            ],
            crossAxisAlignment: CrossAxisAlignment.start,
          ),
        );
      }
    }
    return Container();
  }
}

I am having the same prob. If u solved can you share the solution?