Firebase read from the database resulting in repeating the contents of last uploaded document instead of all documents

31 views Asked by At

I was trying to build a social media app.In my home page I was displaying other people posts.But its displaying the last uploaded post repeatedly rather than displaying all posts.

This is cloud firestore database structure database structure

This is the output I am getting The same post is repeating multiple times

This is my code I have used Stream builder and Listview.builder

I was expecting all posts instead I am getting the recently uploaded pos multiple times displayed

1

There are 1 answers

0
Chamalka Gunawardana On

I think its problem is your code line 77

Map<String,Dynamic> data = snapshot.data...

Try to implement your code like this:

StreamBuilder<QuerySnapshot>(
  stream: FirebaseFirestore.instance.collection('users').snapshots(),
  builder: (context, snapshot) {
    if (snapshot.hasError) {
      return Text('Error: ${snapshot.error}');
    }

    switch (snapshot.connectionState) {
      case ConnectionState.waiting:
        return Center(child: CircularProgressIndicator());
      default:
        return ListView.builder(
          itemCount: snapshot.data!.docs.length,
          itemBuilder: (context, index) {
            final user = snapshot.data!.docs[index].data();
            return ListTile(
              title: Text(user['username']),
              leading: CircleAvatar(
                backgroundImage: NetworkImage(user['profilePic']),
              ),
            );
          },
        );
    }
  },
),