Appearance
EnumByName<T extends Enum>
Annotations: @Since.new("2.15")
Access enum values by name.
Extensions on a collection of enum values, intended for use on the values list of an enum type, which allows looking up a value by its name.
Since enum classes are expected to be relatively small, lookup of byName is performed by linearly iterating through the values and comparing their name to the provided name. If a more efficient lookup is needed, perhaps because the lookup operation happens very often, consider building a map instead using asNameMap:
dart
static myEnumNameMap = MyEnum.values.asNameMap();and then use that for lookups.
Methods
asNameMap() extension
Creates a map from the names of enum values to the values.
The collection that this method is called on is expected to have enums with distinct names, like the values list of an enum class. Only one value for each name can occur in the created map, so if two or more enum values have the same name (either being the same value, or being values of different enum type), at most one of them will be represented in the returned map.
Available on Iterable<E>, provided by the EnumByName<T extends Enum> extension
Implementation
dart
Map<String, T> asNameMap() => <String, T>{
for (var value in this) value._name: value,
};byName() extension
T byName(String name)Finds the enum value in this list with name name.
Goes through this collection looking for an enum with name name, as reported by EnumName.name. Returns the first value with the given name. Such a value must be found.
Available on Iterable<E>, provided by the EnumByName<T extends Enum> extension
Implementation
dart
T byName(String name) {
for (var value in this) {
if (value._name == name) return value;
}
throw ArgumentError.value(name, "name", "No enum value with that name");
}