coerceEnum<T> function

T coerceEnum<T>(
  1. DartObject? object,
  2. String field,
  3. List<T> values, {
  4. required T defaultTo,
})

Reads and returns field on value as an enum from values.

Unlike DartObject#getField, this also traverses super if available.

If the value is missing or not a map, returns defaultTo.

Implementation

T coerceEnum<T>(
  DartObject? object,
  String field,
  List<T> values, {
  required T defaultTo,
}) {
  final enumField = getField(object, field);
  if (enumField == null || enumField.isNull) {
    return defaultTo;
  }
  final enumValue =
      _findEnumByName(enumField, values) ?? _findEnumByIndex(enumField, values);
  if (enumValue == null) {
    throw ArgumentError(
      'Could not determine the enum of $enumField from $values',
    );
  }
  return enumValue;
}