DART - can I cast a string to an enum? DART - can I cast a string to an enum? dart dart

DART - can I cast a string to an enum?


I got annoyed with the state of enums and built a library to handle this:

https://pub.dev/packages/enum_to_string

Basic usage:

import 'package:enum_to_string:enum_to_string.dart';enum TestEnum { testValue1 };main(){    final result = EnumToString.fromString(TestEnum.values, "testValue1");    // TestEnum.testValue1}

Still more verbose than I would like, but gets the job done.


I have came up with a solution inspired from https://pub.dev/packages/enum_to_string that can be used as a simple extension on List

extension EnumTransform on List {  String string<T>(T value) {    if (value == null || (isEmpty)) return null;    var occurence = singleWhere(        (enumItem) => enumItem.toString() == value.toString(),        orElse: () => null);    if (occurence == null) return null;    return occurence.toString().split('.').last;  }  T enumFromString<T>(String value) {    return firstWhere((type) => type.toString().split('.').last == value,        orElse: () => null);  }}

Usage

enum enum Color {  red,  green,  blue,}var colorEnum = Color.values.enumFromString('red');var colorString: Color.values.string(Color.red)


For the Dart enum this is a bit cumbersome.

See Enum from String for a solution.

If you need more than the most basic features of an enum it's usually better to use old-style enums - a class with const members.

See How can I build an enum with Dart? for old-style enums