toEnum<T> method

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

!~~~~~~~~~~~~~~~~~~~~~~~ string to enum ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Converts a string to an enum value of type T.

This method attempts to find an enum value in the provided list enumValues that matches the string representation of the enum's name. The comparison is done against the part of the enum value's string representation after the last dot (.). If no match is found, it returns null.

Example:

enum Color { red, green, blue }

"red".toEnum(Color.values); // Returns Color.red
"green".toEnum(Color.values); // Returns Color.green
"blue".toEnum(Color.values); // Returns Color.blue
"RED".toEnum(Color.values); // Returns null (case-sensitive)
"purple".toEnum(Color.values); // Returns null (not in enum)

Type parameters:

  • T: The enum type.

Parameters:

  • enumValues: A list of enum values of type T to search within.

Returns: The enum value of type T that matches the string, or null if no match is found.

Implementation

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