'Dart default value not set if parameter is null

I am somewhat new to dart and am having trouble with default values for parameters. I am creating a class and in some cases the parameters can be null. In those cases I want to apply the default value. So in the example below the fieldType parameter to TargetField can be null and if that is the case I want to use the default.

The error I am getting is: Unhandled exception: type 'Null' is not a subtype of type 'FieldType'

I can check on the caller side if the value is null and then pass a default value (Comment 1), but I want to set the default value in the TargetField class (Comment 2). I would also prefer to keep the fieldType field not nullable, because it shouldn't ever be null.

Thanks for your help.

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}');
  }

}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source