【问题标题】:How to fix "The operator ‘{0}’ can’t be unconditionally invoked because the receiver can be ‘null’" [duplicate]如何解决“无法无条件调用运算符‘{0}’,因为接收者可以为‘null’”[重复]
【发布时间】:2021-06-02 23:22:32
【问题描述】:

在尝试 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++;
  });
}

现在,我将变量 _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


【解决方案1】:

更新

正如another SO thread 中的建议,a further thread in Github Erik Ernst 说:

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

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

int? _counter;

void _incrementCounter() {
  setState(() {
    if (_counter!=null)
        _counter = _counter! + 1;
  });
}

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


其他修复

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

int? _counter;

void _incrementCounter() {
  setState(() {
    var c = _counter;

    if (c!=null)
      c++;

    _counter = c;
      
  });
}

为什么需要捕获变量?

嗯,整个问题是这样的

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

所以在我的方法中我们

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

最终观察

我是 Dart 的新手,因此我不能 100% 确定,但在我看来,一般,在使用可为空的实例变量时,我的方法是比使用 bang 运算符抛弃无效性更好:

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

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

通过捕获实例变量的值并使用那个本地捕获的值...

可以避免确切的问题...

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

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 2023-03-05
    • 1970-01-01
    • 2021-08-27
    • 2021-09-05
    • 2021-08-05
    相关资源
    最近更新 更多