【问题标题】:Default values for arguments when argument is null?当参数为空时参数的默认值?
【发布时间】:2018-07-18 22:41:34
【问题描述】:

有没有什么方法可以让它返回“默认”而不写出特殊的函数来检查参数并设置它?

void main() {
    Thing stuff = Thing(text: null);
  print(stuff.text);
}


class Thing{
  String text;

  Thing({this.text: "default"});
}

我有一张来自 Firebase 的地图,有时值会为 null,我希望我的类在提供 null 时使用其默认值。

【问题讨论】:

    标签: dart


    【解决方案1】:
    Thing({text}) : this.text = text ?? 'default';
    

    您将需要添加这个小 sn-p,因为构造函数中的默认值仅在指定 no 值时才有效。
    ?? null-aware 运算符将仅在传递的值实际上是 null 时使用 'default' 值(如果没有指定值,也会出现这种情况)。

    【讨论】:

    • 我收到一个错误Fields cannot be initialized in both the parameter list and the initializers.
    • 没关系,如果我完全按照您的示例进行操作。
    猜你喜欢
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 2017-03-06
    • 1970-01-01
    • 2012-08-01
    相关资源
    最近更新 更多