While trying Dart's Sound Null Safety i came up with a problem:
Some Context
Creating a new Flutter project i found the following (and very familiar) piece code
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
Now, i changed the variable _counter
to be nullable and took off the initialization:
int? _counter;
void _incrementCounter() {
setState(() {
_counter++;
});
}
And as expected, i got the following error in the editor:
The operator ‘+’ can’t be unconditionally invoked because the receiver can be 'null'
The Problem
Following the documentation i added the required checking:
if (_counter!=null)
_counter++;
but to my astonishment, the error kept on showing and suggesting
Try making the call conditional (using '?' or adding a null check to the target ('!'))
even though i explicitly am making the call conditionally... so what is wrong?