Member-only story

Dart: Enum to String to Enum

Serialise/Deserialise Dart’s enum with JSON?

Prafulla Singh
1 min readMar 30, 2020

String To Enum: In Dart any Object can get converted in String Using toString(). If we convert a enum to string we get somthing “ClassNameOfEnum.valueNameOfEnum”. we can simply spilt string with “.” and map with string to get valid enum. This can be done as following:

extension EnumParser on String {
T toEnum<T>(List<T> values) {
return values.firstWhere(
(e) => e.toString().toLowerCase().split(".").last == '$this'.toLowerCase(),
orElse: () => null); //return null if not found
}
}

Enum to String:

This is very simple.

enum Number {
ONE,
TWO,
THREE
}
Number num = "ONE"
String stringNumber = num.toString().split(".").last;

Do not wish to write code ??

Use: https://pub.dev/packages/enum_to_string

Reference:

--

--

Prafulla Singh
Prafulla Singh

No responses yet