enumValue<T> static method
Safely converts a dynamic value v to an Enum value from the provided values list.
Returns def if no match is found. Supports case-insensitive string matching
and numeric index lookups.
Example:
enum Status { active, inactive }
JsonCare.enumValue("ACTIVE", Status.values, def: Status.inactive); // Status.active
JsonCare.enumValue(0, 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;
if (v is int) {
if (v >= 0 && v < values.length) return values[v];
}
final String s = v.toString().trim().toLowerCase();
final parsedIdx = int.tryParse(s);
if (parsedIdx != null && parsedIdx >= 0 && parsedIdx < values.length) {
return values[parsedIdx];
}
for (final value in values) {
final name =
value is Enum ? value.name : value.toString().split('.').last;
if (name.toLowerCase() == s) {
return value;
}
}
_logMismatchedType("Enum", v);
return def;
}