【发布时间】: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