0

we are making home page like Instagram and I want to show only the user post for now. the code was like this

 StreamBuilder(
    stream: FirebaseFirestore.instance.collection('posts').orderBy("datePublished", descending: true).snapshots(),
    builder: (context,
        AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
         return const Center(
             child: CircularProgressIndicator(),
         );
      }
    return PageView.builder(/*the rest of the code ...*/);

it worked but it shows all the post so I added this

.where('uid', isEqualTo: uid)

and it looks like this inside Widget build

var uid = FirebaseAuth.instance.currentUser!.uid;

inside body like this

StreamBuilder(
    stream: FirebaseFirestore.instance.collection('posts').where('uid', isEqualTo: uid).orderBy("datePublished", descending: true).snapshots(),
    builder: (context,
        AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
         return const Center(
             child: CircularProgressIndicator(),
         );
      }
    return PageView.builder( //to make the page scroll
      itemCount: snapshot.data!.docs.length,/*the rest of the code*/);

and it shows an error in line

itemCount: snapshot.data!.docs.length, saying Null check operator used on a null value

the database look like this

enter image description here

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Shatha
  • 35
  • 6
  • Have you created the corresponding [index](https://stackoverflow.com/questions/50305328/firestore-whereequalto-orderby-and-limit1-not-working)? – Alex Mamo May 04 '22 at 06:03

1 Answers1

0

The error indicates that snapshot.data is null. This could happen when snapshot.connectionState is equal to ConnectionState.none when the stream is initialized and should be protected against.

Depending on how the PageView is set up you could handle this by changing that line to itemCount: snapshot.data?.docs.length ?? 0, which will pass 0 when snapshot.data is null.

Another way would be to check for the null value beforehand.

if (snapshot.data == null) {
    return SomeWidget():
} else {
    return PageView.builder( //to make the page scroll
      itemCount: snapshot.data!.docs.length,/*the rest of the code*/
    );
}
a.shak
  • 221
  • 1
  • 3
  • Thank you sooo much. I tried this (itemCount: snapshot.data?.docs.length ?? 0) and it worked <3 – Shatha May 04 '22 at 19:38