【问题标题】:In dart what is the difference between ? and ! for nullable types?在飞镖中有什么区别?和 !对于可空类型?
【发布时间】:2022-11-16 18:55:45
【问题描述】:

我是 Dart 和 Flutter 的新手。

在飞镖中,使用之间有什么区别?和 !对于可为空的类型?

validator: ((value) {
   if (value?.isEmpty) {
        return "Field is required";
   }
        return null;
   }),


validator: ((value) {
   if (value!.isEmpty) {
        return "Field is required";
   }
        return null;
   }),

提前致谢!

【问题讨论】:

  • 你检查过dart.dev/null-safety了吗?
  • 我很好奇为什么一个会被另一个@VincentDR 使用
  • 在可空变量上使用 bang 运算符 (!) 意味着该变量在该上下文中不能是 null。使用 ”?”意味着如果变量是null那么将返回null而不是抛出错误。在这种情况下,if 条件应更改为类似 if (value?.isEmpty ?? true) 的内容,这意味着对于 null 和空值,条件均为 true

标签: flutter dart mobile


【解决方案1】:

关于它的好话题:What is Null Safety in Dart?

但简而言之,您使用“?”当您想允许该值为 null 并相应地使用它时,如下所示:

String? test;
if (test?.isEmpty == true) { // And is not null, but you don't need to check it
  // If null, will never pass there but without error
}

并使用“!”当你想确保有一个不可空的值时,像这样:

String? test;
if (test!.isEmpty == true) { // Will throw an error
  ...
}

【讨论】:

    【解决方案2】:

    主要区别在于使用 ?你是说价值或许空,而 !正在通知编译器您确定它不能为空。

    价值?说也许它是空的,而价值!不可为空。

    【讨论】:

      猜你喜欢
      • 2019-09-30
      • 2023-01-10
      • 2019-06-13
      • 2014-02-19
      • 2015-05-30
      • 2019-10-12
      • 1970-01-01
      • 2021-06-04
      • 2010-10-02
      相关资源
      最近更新 更多