我找不到像在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)
}有没有一种方法可以像其他空安全语言一样以干净的方式安全地解包?或者我们必须总是在null-check之后强制解开变量?
发布于 2021-03-11 22:06:47
您的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官方网站上关于空安全性的文章:https://dart.dev/null-safety
发布于 2021-07-18 11:01:37
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中可能为空。
https://stackoverflow.com/questions/66583766
复制相似问题