toEnum<T> method

T? toEnum<T>(
  1. List<T> enumValues
)

Tries to parse the string into a specified enum type T. Returns null if the parsing fails. This method requires the list of all enum values enumValues to check against.

Example:

enum Colors { red, green, blue }
print('green'.toEnum(Colors.values)); // Output: Colors.green
print('purple'.toEnum(Colors.values)); // Output: null

Implementation

T? toEnum<T>(List<T> enumValues) =>
    enumValues.firstWhereOrNull((e) => e.toString().split('.').last == this || e.toString() == this);