【问题标题】:How to increment/decrement a nullable expression in Dart's Sound Null Safety: `<nullable_variable>!++`?如何在 Dart 的 Sound Null Safety 中增加/减少可为空的表达式:`<nullable_variable>!++`?
【发布时间】:2021-06-03 09:20:36
【问题描述】:

我在 Dart 中使用 Sound Null Safety,并且我有以下代码

int? _counter;

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

现在,由于 _counter 不是局部变量,它不能被提升(请参阅this other thread 了解原因),所以我必须告诉 Dart 我确定 _counter 不为空通过添加 bang 运算符 (!)。于是我写了

_counter!++;

但这不起作用:我收到错误消息

对不可赋值表达式的非法赋值。

那么,有没有一种方法可以解决这个问题而无需显式编写

_counter = _counter! + 1;

【问题讨论】:

    标签: flutter dart dart-null-safety


    【解决方案1】:

    它正在按预期工作今天,如果您将int? 保留为_counter 的类型,则必须使用_counter = _counter! + 1;

    将来这可能会改变提案Dart Null-Asserting Composite Assignment

    【讨论】:

    猜你喜欢
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    • 2021-08-30
    相关资源
    最近更新 更多