Home > Back-end >  getting null error when using .where('uid', isEqualTo: uid) in firebase flutter
getting null error when using .where('uid', isEqualTo: uid) in firebase flutter

Time:05-05

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

CodePudding user response:

The error indicates that snapshot.data is null. This could happen happen 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*/
    );
}
  • Related