Search code examples
fluttergoogle-cloud-firestorestream-builder

Flutter Streambuilder is duplicating items


I have a StreamBuilder connected to a List and the List gets its data from Firebase, but every there is an Event in my Database the items in my Streambuilder get Duplicated.

Here is my StreamBuilder code:

StreamBuilder(
                  stream: masterListStart().asStream(),
                  builder: (context, snapshot) {
                    //return coursesList.length == 0
                    return finishedLoadingList
                        ? ListView.builder(
                            scrollDirection: Axis.horizontal,
                            shrinkWrap: true,
                            itemCount: storysList.length,
                            itemBuilder: (context, index) {
                              //
                              StoryItems data = storysList[index];
                              //
                              return StoryItems(
                                data: data,
                              );
                            },
                          )
                        : CircularProgressIndicator();
                  },
                ),

How I can prevent the StreamBuilder from doing this?


Solution

  • Instead of using finishedLoadingList, you can simply check your snapshot connectionState as following

    StreamBuilder(
      stream: masterListStart().asStream(),
      builder: (context, snapshot) {
        //return coursesList.length == 0
        return (ConnectionState.done == snapshot.connectionState) ? ListView.builder(
          scrollDirection: Axis.horizontal,
          shrinkWrap: true,
          itemCount: storysList.length,
          itemBuilder: (context, index) {
            //
            StoryItems data = storysList[index];
            //
            return StoryItems(
              data: data,
            );
          },
        ) : CircularProgressIndicator();
      },
    ),