Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

firebase - Flutter Listview duplicates random element instead of adding new element on new data

I'am trying to create something like feed with Flutter and Firebase and I want to order posts by their 'postedAt' value but the problem is when I use collection.orderBy() it is not working properly. It adds new post to the random place at the feed and gives it a imageURL of random existing post (or I think it just duplicates one item in the feed). I created indexes at Firebase I tried both index types none working. The strange thing is, when I'm adding new post from the phone when my adding completed it just works fine but when listing on the other phone it shows described behaviour.

Edit: when I hot reload it works correct (last added post shows up on the top) Edit: when I removed the orderBy method problem continued.

StreamBuilder(
    stream: FirebaseFirestore.instance
      .collection("users")
      .doc(FirebaseAuth.instance.currentUser.uid)
      .collection("posts")
      .orderBy('postedAt', descending:true)
      .snapshots(),
    builder: (BuildContext context,AsyncSnapshot<QuerySnapshot> snapshot) {
       if (!snapshot.hasData) {
          return Center(
              child: CircularProgressIndicator(),
              );
        }

        if (snapshot.hasError) {
             print("error:" + snapshot.error.toString());
         }



     List<Post> posts = [];

     posts = snapshot.data.docs.map((postDoc) {
          return Post.fromDoc(postDoc);
      }).toList();

     if (posts.isEmpty) {
         return Center(
            child: Text("No posts"),
          );
     }

     return ListView.builder(
          cacheExtent: 4000,
          itemCount: posts.length,
          itemBuilder: (BuildContext context, int index) {
            return PostWidget(
                post: posts[index],
                );
            },
          );
        },
     )

my indexes:

Composite index single index

screenshot of the document: document ss

question from:https://stackoverflow.com/questions/65932248/flutter-listview-duplicates-random-element-instead-of-adding-new-element-on-new

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I solved this issue. I thought that if it is duplicating the elements, may be it cannot seperate them. and added key paramater to PostWidget so it worked.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...