【问题标题】:How to safely unwrap optional variables in dart?如何安全地解开飞镖中的可选变量?
【发布时间】:2021-06-09 12:26:54
【问题描述】:

我找不到像我们在 swift 中那样安全地解开可选变量的方法

var myString: String?
if let myString = myString {
  print(myString) // myString is a string
}

或者在 Kotlin 中

var myString: String?
if (myString != null) {
   print(myString) // myString is not null
}

// or
myString?.let {
   print(it) // myString is not null
}

在 Dart 中,我必须执行以下操作,这看起来不太好:

String? myString;
if (myString != null) {
   print(myString); // myString still an optional
   print(myString!); // myString is now a String! (because of the force unwrap)
}

有没有办法像其他空安全语言一样以干净的方式安全地展开?或者我们必须总是在空检查后强制解包变量?

【问题讨论】:

  • 你确定你做的 Dart 例子吗?您是如何确定在您的 if 之后 Dart 仍将 myString 视为可为空的?
  • @julemand101 我的意思是,即使我们知道它不是,分析器仍然将其视为可选字符串。

标签: dart


【解决方案1】:

您的 Dart 示例似乎不完整,但如果没有更多上下文,很难说出哪里出了问题。如果myString 是本地变量,它将被提升。你可以看到这个例子:

void main(){
  myMethod(null); // NULL VALUE
  myMethod('Some text'); // Non-null value: Some text
}

void myMethod(String? string) {
  if (string != null) {
    printWithoutNull(string);
  } else {
    print('NULL VALUE');
  }
}

// Method which does not allow null as input
void printWithoutNull(String string) => print('Non-null value: $string');

如果我们谈论类变量,情况就不同了。您可以在此处查看有关该问题的更多信息:Dart null safety doesn't work with class fields

解决该问题的方法是将类变量复制到方法中的局部变量中,然后使用 null 检查提升局部变量。

总的来说,我会推荐阅读 Dart 官网关于 null 安全性的文章:https://dart.dev/null-safety

【讨论】:

  • 谢谢!是的,我真正的问题是类变量,我会看看那个帖子!
【解决方案2】:
void main(List<String> args) {
  var x;
  if (x != null) {
    // Since you've already checked, the following statement won't give an error.
    print(x!);
  } else {
    print('ERROR');
  }
}

我想这就是你可以安全地解开 Dart 中可以为 null 的选项或变量的方法。

【讨论】:

    猜你喜欢
    • 2021-10-11
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    相关资源
    最近更新 更多