有没有办法让它返回“默认”,而无需编写特殊函数来检查参数并设置它?
void main() {
Thing stuff = Thing(text: null);
print(stuff.text);
}
class Thing{
String text;
Thing({this.text: "default"});
}
我有一张来自 Firebase 的 map ,有时值将为 null,我希望我的类在提供 null 时使用其默认值。
最佳答案
Thing({text}) : this.text = text ?? 'default';
您需要添加这个小代码片段,因为构造函数中的默认值仅在没有指定时才起作用。
如果传递的值实际上是 null<,
(如果未指定值,情况也会如此)。??
null-aware 运算符将仅使用 'default'
值
关于dart - 当参数为空时参数的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51411956/