【问题标题】:Dart, Identifier with exclamation mark in the backDart,后面带感叹号的标识符
【发布时间】:2021-04-21 06:09:08
【问题描述】:

最近我一直在用颤振开发移动应用程序,当我查看 TickerProvider 的源代码时,我看到了以下几行:

mixin SingleTickerProviderStateMixin<T extends StatefulWidget> on State<T> implements TickerProvider {
Ticker? _ticker;

  @override
  Ticker createTicker(TickerCallback onTick) {
    ...
    _ticker = Ticker(onTick, debugLabel: kDebugMode ? 'created by $this' : null);
    return _ticker!;
  }

...
}

我对这条线很感兴趣:

return _ticker!;

我见过前面有感叹号的布尔标识符,这意味着它将返回它的相反值,但我从未见过这个。谁能告诉我这是做什么的?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    这是 Dart 具有的 null 安全性的一部分。

    你可以阅读它here

    If you’re sure that an expression with a nullable type isn’t null, you can add ! to make Dart treat it as non-nullable
    

    例子:

    int? aNullableInt = 2;
    int value = aNullableInt!; // `aNullableInt!` is an int.
    // This throws if aNullableInt is null.
    

    【讨论】:

      【解决方案2】:

      为了更好地理解(通过类比算法本身的作用)。
      此运算符充当以下内联内部函数(至少类似):

      T cast<T>(T? value) {
        if (value == null) {
          throw _CastError('Null check operator used on a null value');
        } else {
          return value;
        }
      }
      

      附言

      忘记添加了。
      根据运行时产生的错误信息,我们可以推断出这个算子叫做Null check operator,这可能意味着它会检查null的值,如果是null则抛出异常。

      没有魔法!

      【讨论】:

        猜你喜欢
        • 2021-10-23
        • 2019-11-11
        • 2013-09-21
        • 1970-01-01
        • 2019-09-16
        • 1970-01-01
        • 2012-01-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多