Home > Enterprise >  Null check operator used on a null value error when fetching JSON
Null check operator used on a null value error when fetching JSON

Time:11-14

I do not get this.

  builder: (context, snapshot) {
    if (snapshot.data != null && widget.stored!.b) {
      return new GridView.count(
          children: List.generate(snapshot.data!.length, (index) {
            return _buildCell(snapshot.data![index]);
          }));
    }
  });

So, to recap:

if (snapshot.data != null && widget.stored!.b)

This snippet is where the error seems to be. I am trying to get 'b' and show only those posts (when true).

And I have this in my Stored.dart:

class Stored extends Base {
  late bool b;
}

As you can see, I am trying to check if the string = "1" and if so, assign true to it:

  Stored(Map<String, dynamic> json) : super(json) {
    post-number = json["posts"];
    bool b = post-number == "1";
}

With the JSON response being:

{"posts":"1"}';

I do not get what I am doing wrong? I am trying to only show the posts that number 1 in it, but when trying to fetch, I am getting the Null check operator used on a null value error. Why is that?

CodePudding user response:

The error means that widget.stored is null. The ! tells the compiler that it should not be nullable. So use the conditional property access instead:

widget.stored?.b == true
  • Related