enumValue<T> static method

T enumValue<T>(
  1. dynamic v,
  2. List<T> values, {
  3. required T def,
})

Safely converts a dynamic value v to an Enum value from the provided values list.

Returns def if no match is found. Case-insensitive matching against the short name of the enum.

Example:

enum Status { active, inactive }
JsonCare.enumValue("ACTIVE", Status.values, def: Status.inactive); // Status.active

Implementation

static T enumValue<T>(dynamic v, List<T> values, {required T def}) {
  if (v == null) return def;
  final String s = v.toString().toLowerCase();
  for (final value in values) {
    if (value.toString().split('.').last.toLowerCase() == s) {
      return value;
    }
  }
  _logMismatchedType("Enum", v);
  return def;
}