【发布时间】:2021-06-26 10:52:59
【问题描述】:
如何在 Flutter 中进行 null 检查或创建 null 安全块?
这是一个例子:
class Dog {
final List<String>? breeds;
Dog(this.breeds);
}
void handleDog(Dog dog) {
printBreeds(dog.breeds); //Error: The argument type 'List<String>?' can't be assigned to the parameter type 'List<String>'.
}
void printBreeds(List<String> breeds) {
breeds.forEach((breed) {
print(breed);
});
}
如果你尝试用 if 情况包围它,你会得到同样的错误:
void handleDog(Dog dog){
if(dog.breeds != null) {
printBreeds(dog.breeds); //Error: The argument type 'List<String>?' can't be assigned to the parameter type 'List<String>'.
}
}
如果您创建一个新属性然后对其进行空检查,它可以工作,但是每次您想进行空检查时都创建新属性变得很麻烦:
void handleDog(Dog dog) {
final List<String>? breeds = dog.breeds;
if (breeds != null) {
printBreeds(breeds); // OK!
}
}
有没有更好的方法来做到这一点?
像 kotlin 中的 ?.let{} 语法一样吗?
【问题讨论】:
标签: flutter dart nullable null-check dart-null-safety