【问题标题】:Is there any NotNull annotation in dart?飞镖中是否有任何 NotNull 注释?
【发布时间】:2021-10-16 18:29:37
【问题描述】:

我有这个小班:

class WidgetToImage extends StatefulWidget {
  final Function(GlobalKey key)  builder;

  const WidgetToImage({Key? key, @required this.builder}) : super(key: key);

  @override
  _WidgetToImageState createState() => _WidgetToImageState();
}

这段代码无法编译,因为任何人都可以在构造 WidgetToImage 小部件时为 builder 参数传递空值。我知道我可以使构建器可以为空,但这不是我想要的,因为稍后我必须检查它是否为空等,并且在语义上它没有任何意义。必须始终传递有效的构建器。

有什么方法可以在 dart 中注释 this 以避免将 builder 属性转换为可为空的类型?

【问题讨论】:

    标签: dart nullable dart-null-safety


    【解决方案1】:

    如果您使用 Dart 2.12 版,您可以获得 null 安全性作为语言功能。 看来您已经在使用它了,因为您的代码包含 Key?,这是编写“可空”的空安全方式。 另一方面,您的 this.builder 参数应该被标记为 required(空安全代码中的关键字)而不是旧的 @required 注释,所以它看起来不像 有效空安全代码。

    代码应为:

    class WidgetToImage extends StatefulWidget {
      final Function(GlobalKey key)  builder;
    
      const WidgetToImage({Key? key, required this.builder}) : super(key: key);
    
      @override
      _WidgetToImageState createState() => _WidgetToImageState();
    }
    

    然后将null 作为参数传递给builder 会导致空安全代码的编译时错误。 (旧的非 null 安全代码仍然可以通过 null 逃脱,但那时他们正在自找麻烦。)

    你可以添加一个断言:

      const WidgetToImage({Key? key, required this.builder}) 
          : assert(builder as dynamic != null), 
            super(key: key);
    

    这将告诉人们针对您的库进行开发时不要从非空声音代码中传递null,但只能在启用断言的情况下进行开发。

    【讨论】:

    • 我的意思是如果有任何“编译时间”检查。而不是运行时。我知道我可以使用 assert 但这不是我对现代类型语言的期望,它有一些非常方便的注释。对于所需的关键字,谢谢。没有注意到他们添加了那个。
    • @Notbad Dart 2.12 的空安全特性的要点是使用类型系统添加编译时检查。见dart.dev/null-safety/understanding-null-safety
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    • 1970-01-01
    • 2014-09-05
    • 2020-05-15
    • 1970-01-01
    • 2019-08-04
    相关资源
    最近更新 更多