skip to Main Content

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

Answers


  1. 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();
    
    Login or Signup to reply.
  2. 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;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search