Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment/decrement a nullable expression in Dart's Sound Null Safety: `<nullable_variable>!++`?

I am using the Sound Null Safety in Dart, and i have the following code

int? _counter;

void _incrementCounter() {
  setState(() {
    if (_counter!=null)
      _counter++;
  });
}

Now, since _counter is not a local variable, it can not be promoted (see this other thread to see why), so i have to tell Dart i am sure _counter is not null by adding the bang operator (!). Thus i wrote

_counter!++;

but that does not work: i get the error message

Illegal assignment to non-assignable expression.

So, is there a way to get around this without the need to explicitly write

_counter = _counter! + 1;
like image 723
deczaloth Avatar asked Mar 04 '21 17:03

deczaloth


1 Answers

It's working as intended today and you have to use _counter = _counter! + 1; if you keep int? as type of _counter.

In the future this could change regarding the proposal Dart Null-Asserting Composite Assignment .

like image 181
Alexandre Ardhuin Avatar answered Sep 19 '22 05:09

Alexandre Ardhuin