在尝试Dart的Sound Null Safety时,我遇到了一个问题:
一些背景
创建一个新的Flutter项目我发现了以下(并且非常熟悉的)片段代码
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++;
});
}
现在,我将变量更改为_counter
可为空并取消初始化:
int? _counter;
void _incrementCounter() {
setState(() {
_counter++;
});
}
正如预期的那样,我在编辑器中收到以下错误:
不能无条件调用运算符“+”,因为接收者可以为“null”
问题
在文档之后,我添加了所需的检查:
if (_counter!=null)
_counter++;
但令我惊讶的是,错误不断显示和提示
尝试使调用有条件(使用'?'或向目标添加空检查('!'))
即使我明确地有条件地拨打电话......那有什么问题?