我對飛鏢有點陌生,并且在引數的默認值方面遇到了麻煩。我正在創建一個類,在某些情況下引數可以為空。在這些情況下,我想應用默認值。因此,在下面的示例中,TargetField 的 fieldType 引數可以為空,如果是這種情況,我想使用默認值。
我得到的錯誤是:未處理的例外:型別'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}');
}
}
uj5u.com熱心網友回復:
如果省略引數,您可以使建構式使用相同的默認值,或者 null通過創建默認引數null并添加邏輯以回退到成員的所需默認值。請注意,構造引數可以為空,但成員不需要。例如:
class TargetField {
FieldType fieldType;
final String fieldName;
TargetField({required this.fieldName, FieldType? fieldType})
: fieldType = fieldType ?? FieldType.string;
這種技術對于使用非const值作為默認引數也很有用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/426604.html
