Home > front end >  Null check operator used on a null value FLUTTER 2.10
Null check operator used on a null value FLUTTER 2.10

Time:04-08

I have get this error (Null check operator used on a null value) Exception caught by widgets library when use where condition and order by query together on firebase,

result = FirebaseFirestore.instance
      .collection('posts')
      .where('place_city', isEqualTo: placeCity)
      .orderBy('likes', descending: true)
      .snapshots();

if I remove where statement or order by it will work, like this

result = FirebaseFirestore.instance
      .collection('posts')
      //.where('place_city', isEqualTo: placeCity)
      .orderBy('likes', descending: true)
      .snapshots();

CodePudding user response:

Before assigning the data to widgets, validate whether that field value is null or not. Only then assign to the widget.

example 1: Validate before assigning the data to widget

if(snapshot.data != null) {
  return Text(snapshot.data.name);
}

example 2: Handle directly in the widget

Text(snaphot.data.name ?? '');

CodePudding user response:

After storing the snapshots in result, you might be using or trying to access the data, where you probably have used the null check operator.

Please share the entire code to evaluate, or debug the code at the place where you have added null operator.

CodePudding user response:

You have this error because of null safety.

When you add:

.where('place_city', isEqualTo: placeCity)

you affect placeCity to isEqualTo, but placeCity can be null. That's why you get this error.

To correct this error you have to ensure that placeCity can't be null.

For this, when you affect placeCity, do like this:

placeCity = something ?? 'default value'

You can also, if you are shure that placeCity will never be null use the ! operator, like this:

.where('place_city', isEqualTo: placeCity!)

it tell dart that placeCity is never null and thus error disappear.

  • Related