【发布时间】:2021-06-02 23:22:32
【问题描述】:
在尝试 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”
问题
在the documentation 之后,我添加了所需的检查:
if (_counter!=null)
_counter++;
但令我惊讶的是,错误不断显示和提示
尝试使调用有条件(使用“?”或向目标添加空检查(“!”))
即使我明确地有条件地进行调用...那么有什么问题?
【问题讨论】:
-
if (_counter != null) _counter = _counter! + 1; -
@Dude,“使用 ! 会失去静态安全性” [dart.dev/null-safety/…
标签: flutter dart dart-null-safety