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

Issue

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;

Solution

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
.

Answered By – Alexandre Ardhuin

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.