如何修复“无法无条件调用运算符 '{0}',因为接收器可以为 'null'”

Dec*_*oth 7 dart flutter dart-null-safety

在尝试DartSound 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++;
  });
}
Run Code Online (Sandbox Code Playgroud)

现在,我将变量更改为可_counter并取消初始化:

int? _counter;

void _incrementCounter() {
  setState(() {
    _counter++;
  });
}
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,我在编辑器中收到以下错误:

无法无条件调用运算符“+”,因为接收器可以为“null”

问题

按照文档,我添加了所需的检查:

if (_counter!=null)
        _counter++;

Run Code Online (Sandbox Code Playgroud)

但令我惊讶的是,错误一直在显示和暗示

尝试使调用有条件(使用 '?' 或向目标添加空检查 ('!'))

即使我明确地有条件拨打电话......那有什么问题呢?

Dec*_*oth 10

更新

@suragch 请让我知道这个问题已经在 SO 中得到了答案。在另一个 SO 线程,引用了 Github 中的另一个线程,其中 Erik Ernst 说:

类型提升仅适用于局部变量......实例变量的提升是不合理的,因为它可能被一个运行计算并在每次调用时返回不同对象的 getter 覆盖。参见 dart-lang/language#1188用于讨论类似于类型提升但基于动态检查的机制,以及一些相关讨论的链接。

所以,有了这个解释,现在我看到只有局部变量可以(到目前为止?)被提升,因此我的问题可以通过写作来解决

int? _counter;

void _incrementCounter() {
  setState(() {
    if (_counter!=null)
        _counter = _counter! + 1;
  });
}
Run Code Online (Sandbox Code Playgroud)

有关替代修复,请参阅下面我的原始答案。


其他修复

我最终通过捕获方法内部实例变量的值解决了这个问题,如下所示:

int? _counter;

void _incrementCounter() {
  setState(() {
    if (_counter!=null)
        _counter = _counter! + 1;
  });
}
Run Code Online (Sandbox Code Playgroud)

为什么需要捕获变量?

嗯,整个问题是

类型提升仅适用于局部变量......实例变量的提升是不合理的,因为它可能被一个运行计算并在每次调用时返回不同对象的 getter 覆盖

所以在我的方法中,我们

  • 捕获实例变量的值
  • 然后我们检查 是否为空。
  • 如果该值不是空值,那么我们对局部变量进行操作,该变量现在通过空值检查被正确提升。
  • 最后,我们将新值应用于实例变量。

最终观察

我是Dart 的新手,所以我不确定我要写什么,但对我来说,一般来说,当使用可为空的实例变量时,我的方法比使用 bang 运算符来抛弃空性更好:

通过抛弃空性,您忽略了提升实例变量的主要问题,即

它可以被一个 getter 覆盖,该 getter 运行计算并在每次调用时返回一个不同的对象......

这确切是什么问题,是避免捕获实例变量的值,并与合作本地捕获的值...

如果我错了请告诉我...


归档时间:

查看次数:

17287 次

最近记录:

4 年,8 月 前