asEnum<T> method

T asEnum<T>(
  1. String key,
  2. List<T> enumValues, {
  3. required T def,
  4. String stringCleaner(
    1. String data
    )?,
})

Retrieves an enum value of type T associated with the key. If the key does not exist or the value cannot be parsed as an enum, returns the def value.

key The key in the map to retrieve the value from. enumValues A list of possible enum values. def The default value to return if the key is not found or the value cannot be parsed. This must be specified. stringCleaner An optional function to clean or modify the string representation of the value before comparison.

Returns: The enum value associated with the key or def if not found or cannot be parsed.

Implementation

T asEnum<T>(
  String key,
  List<T> enumValues, {
  required T def,
  String Function(String data)? stringCleaner,
}) {
  if (keys.contains(key) && this[key] != null) {
    T res = enumValues.firstWhere(
      (element) {
        String value = this[key];
        if (stringCleaner != null) {
          value = stringCleaner(value);
        }
        return element.toString() == '$T.$value';
      },
      orElse: () => def,
    );
    return res;
  }

  return def;
}