enumDecode<T> function Null safety

T enumDecode<T>(
  1. Map<T, dynamic> enumValues,
  2. dynamic source,
  3. {required T unknownValue}
)

Implementation

T enumDecode<T>(
  Map<T, dynamic> enumValues,
  dynamic source, {
  required T unknownValue,
}) {
  if (source == null) {
    throw ArgumentError('A value must be provided. Supported values: '
        '${enumValues.values.join(', ')}');
  }

  final value = enumValues.entries.singleWhere((e) => e.value == source).key;

  if (value == null && unknownValue == null) {
    throw ArgumentError('`$source` is not one of the supported values: '
        '${enumValues.values.join(', ')}');
  }
  return value ?? unknownValue;
}