Home > Enterprise >  Flutter StreamBuilder flashes with data then clears
Flutter StreamBuilder flashes with data then clears

Time:09-22

I'm trying to build a page in Flutter that shows all the comments made by a user. For some reason, this stream builder loads the data, flashes it briefly, then acts as if there is no data. I'm sure it has something to do with the way my query/stream is built. Thanks for any help! Update I've discovered it is when I use the ".where" query that causes the problem.

This works great: FirebaseFirestore.instance.collectionGroup('comments').snapshots()

This loads correctly for about half a second then has no data: FirebaseFirestore.instance.collectionGroup('comments').where('uid', equalTo: uid).snapshots()

Code:

child: StreamBuilder<QuerySnapshot>(
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          List<CommentCard> commentList = [];
          final comments = snapshot.data!.docs;
          for (var comment in comments) {
            commentList.add(CommentCard(
                comment: Comment.fromSnapshot(
                    comment, comment.reference.parent.parent!.id)));
          }
          commentList.sort();

          return Column(children: commentList);
        }
        return const Text("You have made no comments");
      },
      stream: FirebaseFirestore.instance
          .collectionGroup('comments')
          .where('uid', isEqualTo: currentUser.uid)
          .snapshots(),
    ),

CodePudding user response:

Try to check if you have any errors while fetching data from the network, as you may know retrieving data from network takes a while.

Try this code, hope it helps you.

 return StreamBuilder(
    stream: FirebaseFirestore.instance.collectionGroup('comments').where('uid', isEqualTo: currentUser.uid)
    .snapshots(),
    builder: (context, snapshot) {
      if(snapshot.hasData)
        {
          List<CommentCard> commentList = [];
          final comments = snapshot.data!.docs;
          for (var comment in comments) {
            commentList.add(CommentCard(
                comment: Comment.fromSnapshot(
                    comment, comment.reference.parent.parent!.id)));
          }
          commentList.sort();

          return Column(children: commentList);
    }
      else if(snapshot.hasError)
        {
          return Text("You have no Comments");
        }
      else{
        return CircularProgressIndicator();
      }
 }
 );

CodePudding user response:

While others had good input on improvments, the main source of my problem was that I did not have an index setup for the collectionGroup. Good video: https://www.youtube.com/watch?v=fQ4u1J717ys

  • Related