【问题标题】:Dart default value not set if parameter is null如果参数为 null,则未设置 Dart 默认值
【发布时间】:2022-06-19 17:58:34
【问题描述】:

我在参数的默认值方面遇到了问题。我正在创建一个类,在某些情况下参数可以为空。在这些情况下,我想应用默认值。因此,在下面的示例中,TargetField 的 fieldType 参数可以为 null,如果是这种情况,我想使用默认值。

我得到的错误是: 未处理的异常: “Null”类型不是“FieldType”类型的子类型

我可以在调用方检查该值是否为空,然后传递一个默认值(注释 1),但我想在 TargetField 类中设置默认值(注释 2)。我还希望 fieldType 字段不能为空,因为它不应该为空。

enum FieldType {
  string,
  int,
  date,
  array,
  lookup,
  map
}

main() {
  Map<String, Map> myMap = {
    'target0': { 'type': FieldType.string},
    'target1': { 'static': 'hello'},
    'target2': { 'static': 'goodbye'},
    'target3': { 'type': FieldType.date},
    };

  print('running now');
  myMap.forEach((k, v) {
    print('running now, $k : $v');
    TargetField tf = TargetField(fieldName: k, fieldType: v['type']);

    // Comment 1: Would like to avoid doing this, would be more comfortable doing
    // something on the TargetField side to set the default value, not the caller.

    // TargetField tf = TargetField(fieldName: k,
    //     fieldType: (v['type'] != null) ? v['type'] : FieldType.string);
    tf.printType();
  }
  );
}

class TargetField {

  FieldType fieldType;
  final String fieldName;

  TargetField({required this.fieldName, this.fieldType = FieldType.string}) {
    //Comment 2: Can I do something here to set the value to the default value if the
    //parameter passed is null?
  }

  printType() {
    print('$fieldName type = ${fieldType.name}');
  }

}

【问题讨论】:

    标签: dart parameters null default


    【解决方案1】:

    如果省略参数,您可以使构造函数使用相同的默认值 null,方法是设置默认参数null 并添加逻辑以回退到成员的所需默认值.请注意,构造参数可以为空,但成员不需要。例如:

    class TargetField {
      FieldType fieldType;
      final String fieldName;
    
      TargetField({required this.fieldName, FieldType? fieldType})
        : fieldType = fieldType ?? FieldType.string;
    

    这种技术对于using non-const values as default arguments 也很有用。

    【讨论】:

    • 完美,谢谢。我知道有办法做到这一点,但就是不能把它放在一起。并不是说它很重要,但你在哪里有字符串?它应该是 FieldType?。再次感谢。
    • 糟糕,我把它们弄混了,因为参数顺序与成员顺序不匹配。固定。
    猜你喜欢
    • 2019-10-22
    • 1970-01-01
    • 2018-06-20
    • 2013-04-28
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 2016-09-01
    相关资源
    最近更新 更多