Search code examples
firebasefluttergoogle-cloud-firestorestream-builder

Streambuilder is not updating in Flutter


I am using Streambuilder and loading Snapshot from firebase. After loading the snapshot, I am putting my data into Post.dart where I made widget structure. My code can get the data, but when I delete the one of the post from the firebase, it still show the same posts, but last one disappears instead of the deleted one. However, if I change my page and come back, right one is deleted and everything is fine. So I think flutter knows that I am changing my firebase, but does not know how to map it into my Post. Any thought?

 StreamBuilder(
              stream: FirebaseFirestore.instance
                      .collection("timeline")
                      .doc(widget.currentUser.id)
                      .collection('timelinePosts')
                      .orderBy('timestamp', descending: true)
                      .snapshots()
              builder: (BuildContext context,
                  AsyncSnapshot<QuerySnapshot> streamSnapshot) {
                var items = streamSnapshot.data != null &&
                        streamSnapshot.data.docs != null
                    ? streamSnapshot.data.docs
                    : [];

                List<Post> posts =
                    items.map((doc) => Post.fromDocument(doc)).toList();

                return !streamSnapshot.hasData ||
                        streamSnapshot.connectionState ==
                            ConnectionState.waiting
                    ? Center(
                        child: CircularProgressIndicator(),
                      )
                    : Column(
                        children: posts);
              })

and Post is something like

 @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
      ...
      ],
    );
  }

Solution

  • You need to provide a unique key to your post item widgets so that when flutter rebuilds the column, it is able to differentiate between the old posts and the new list of posts. Basically it has to do with how flutter decides to rebuild certain elements and when.

    If you want to test whether a unique key can solve the problem I usually start by assigning a key like this to the post widgets:

    key: Key("${Random().nextDouble()}"),
    

    And seeing if that changes anything. If it fixes it, you can try a more efficient key like a combination of the properties of each element.