12

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;
deczaloth
  • 7,094
  • 4
  • 24
  • 59

1 Answers1

22

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 .

Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132
  • If you came here and would like to see this change in syntax please go to https://github.com/dart-lang/language/issues/1113# and add some noise! – deczaloth May 26 '21 at 13:18
  • this is something very basic and fundamental, but sometimes in the rush of everyday life we forget details like this. thank you friend. – Felipe Sales May 25 '22 at 16:47