enumToString<T extends Object> function

String enumToString<T extends Object>(
  1. T enumItem, {
  2. bool withUnderscores = true,
})

Convert enum object to string

Pass in the not nullable enum object and return the part after the dot.

By default this will convert enumItem to string withUnderscores so TestEnum.valueOne will become value_one.

If withUnderscores is false this will leave the result of TestEnum.valueOne equal to valueOne, as well as TestEnum.value_one equal to value_one.

enum TestEnum { valueOneAndTwo }
final eNum = enumToString(TestEnum.valueOneAndTwo);
eNum == 'value_one_and_two'; // true

final eNum = enumToString(TestEnum.valueOneAndTwo, camelCase = true);
eNum == 'valueOneAndTwo'; // true

Implementation

String enumToString<T extends Object>(T enumItem,
    {bool withUnderscores = true}) {
  final splitEnum = enumItem.toString().split('.');
  final enumType = enumItem.runtimeType.toString();

  assert(splitEnum.length == 2 && splitEnum.first == enumType,
      '$enumItem of type $enumType is not a valid enum item');

  return withUnderscores ? splitEnum.last.withUnderscores() : splitEnum.last;
}