Problem when changing a value in an array to null

80 Views Asked by At

I have a list of nullable boolean delared like that :

late List<bool?> isClosed;
...
void initState() {
    super.initState();

    isClosed = widget.gateway.nodes.map((e) {
      return e.devices.firstWhere((element) {
            return element.type == 'lock';
          }).state ==
          'close';
    }).toList();

  }

And later in my code I have to change the value of the array to null just like so :

isClosed[index] = null;
    setState(() {});

I use that for a loading effect when I wait for the response of an API call. But here is my problem, when the previous line is called and null is assigned I got this error :

Unhandled Exception: type 'Null' is not a subtype of type 'bool' of 'value'

I checked index is ok.

Thanks a lot if you have any help with that.

2

There are 2 best solutions below

1
On BEST ANSWER

You need to indicate the type at the mapping, like:

isClosed = widget.gateway.nodes.map<bool?>((e) {  //notice I added <bool?>
  return e.devices.firstWhere((element) {
        return element.type == 'lock';
      }).state ==
      'close';
}).toList();
0
On

That happens because isClosed is null by itself (using late access in a first instance maybe): Try as follows:

if (isClosed != null &&  isClosed.length > index) isClosed[index] = null;