How to increment/decrement a nullable expression in Dart's Sound Null Safety: `<nullable_variable>!++`?
2,157
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 .
Comments
-
deczaloth over 1 year
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 about 3 yearsIf you came here and would like to see this change in syntax please go to github.com/dart-lang/language/issues/1113# and add some noise!
-
Felipe Sales about 2 yearsthis is something very basic and fundamental, but sometimes in the rush of everyday life we forget details like this. thank you friend.