0

I am trying to display a realtime chat-screen in flutter with with firebase-firestore (equal to the homescreen of whatsapp).

Working: Creating a list of all the contacts "peers". Have a Look at my Listview:

Container(
  child: StreamBuilder(
    stream:
        //FirebaseFirestore.instance.collection('users').snapshots(),
        FirebaseFirestore.instance
            .collection('users')
            .doc(currentUserId)
            .collection('peers')
            .snapshots(),
    builder: (context, snapshot) {
      if (!snapshot.hasData) {
        return Center(
          child: CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(themeColor),
          ),
        );
      } else {
        return ListView.builder(
          padding: EdgeInsets.all(10.0),
          itemBuilder: (context, index) =>
              buildItem(context, snapshot.data.documents[index]),
          itemCount: snapshot.data.documents.length,
        );
      }
    },
  ),
),

not working: Loading specific data for each tile like last message or name. I cant query this at the time of creating my first list (first query returns peer-ids, second returns userdata of a peer-id). My buildItem method consists of another streambuilder, however, as soon as the first streambuilder makes changes, the app freezes.

  Widget buildItem(BuildContext context, DocumentSnapshot document) {
      return StreamBuilder<DocumentSnapshot>(
        stream: FirebaseFirestore.instance
            .collection('users')
            .doc(document.data()['peerId'])
            .snapshots(),
        builder: ...

Is this the proper way to nest streams? Simple Listviews are documented quite well, but i couldn't find a good example on this on google. Any help is appreciated.

1 Answers1

0

Try creating your stream just once in initState and pass it onto this method:

//in initState
peersStream = FirebaseFirestore.instance
            .collection('users')
            .doc(currentUserId)
            .collection('peers')
            .snapshots(),

Then use stream: peersStream in the StreamBuilder.

Also, it is recommended to use widget-classes over methods for widgets: https://stackoverflow.com/a/53234826/5066615

Rohan Taneja
  • 9,687
  • 3
  • 36
  • 48