简体   繁体   中英

Null check operator used on a null value FLUTTER 2.10

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();

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.

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 ?? '');

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM