enumFromString<T> method

T enumFromString <T>(Iterable<T> values, String value)

Returns an enum type from its String representation value. values must be the list of enum types defined by T. It is legal that value be specfied with or without T: .value or value are both legal. Example: enum Fruit { apple, banana }, i.e. T = Fruit. Fruit.apple.toString() will result in "Fruit.apple". Fruit.banana.toString() will result in "Fruit.banana". In order to reconstruct the enum type Fruit.banana from its String representation "Fruit.banana", or just from "banana", do the following: Fruit banana_fruit = enumFromString(Fruit.values, "Fruit.banana"); or just Fruit banana_fruit = enumFromString(Fruit.values, "banana");

Implementation

static T enumFromString<T>(Iterable<T> values, String value) {
  String val = value;
  if (!value.contains(".")) {
    String enumType = values.first.toString().split(".").first;
    val = "$enumType.$value";
  }
  return values.firstWhere((type) => type.toString() == val,
      orElse: () => null);
}