rknell / flutterEnumsToString

Better conversion of ENUMs to string for Flutter / Dart
Other
85 stars 23 forks source link

Enhancement - Capture List<Enum> back from any normal List #21

Closed amoslai5128 closed 4 years ago

amoslai5128 commented 4 years ago

Thank you for creating this nice library, and I want to add some contribution. I've written two versions of Enums from List. I might pull this version to you if it's ok #22 . This would be very useful for converting the enums toJson / fromJson.

Run the Examples:

enum TestEnum { ValueOne, Value2, valueThree }

final testing = fromList(TestEnum.values, ['ValueOne','Value2']);

print("Result: $testing , Type: ${testing.runtimeType}");

//Result: [TestEnum.ValueOne, TestEnum.Value2], Type: List<TestEnum>

Option 1 - cleaner but the performance slower for a little bit? since every time it re-passes again the enumValues into fromString().

static List<T> fromList<T>(List<T> enumValues, List valueList) {
    if (valueList == null || enumValues == null) return null;

    return List<T>.from(
        valueList.map((e) => fromString<T>(enumValues, e.toString())));
}

Option 2 - 🔥Seems slightly faster than 1

static List<T>fromList<T>(List<T> enumValues, List valueList) {
    if (valueList == null || enumValues == null) return null;

    return List<T>.from(valueList.map((e) => e == null
        ? null
        : enumValues.singleWhere((enumItem) {
            return EnumToString.parse(enumItem)?.toLowerCase() ==
                e.toString()?.toLowerCase();
          }, orElse: () => null)));
}

*The fromString() method is from your source code.

rknell commented 4 years ago

Closing thanks to your PR https://github.com/rknell/flutterEnumsToString/pull/22