skip to Main Content

Is there any way to convert a enum to a string and back, without knowing the specific enum. The enums also share a mixin.
For example:

mixin TestMixin {
    String get value; 
}

enum FirstEnum with TestMixin {   
    foo("bar");

    const FirstEnum(this.value);
    @override   
    final String value; 
}

enum SecondEnum with TestMixin {   
    two("car");

    const SecondEnum(this.value);
    @override   
    final String value; 
}

I now have two enums and want to convert them to a string and back, like this

FirstEnum first = FirstEnum.foo;
SecondEnum second = SecondEnum.two;

String firstString = enumToString(first);
String secondString = enumToString(second); // -> enums as strings

Enum firstAgain = stringToEnum(firstString); // firstAgain == first
Enum secondAgain = stringToEnum(secondString); // secondAgain == second


String enumToString(Enum inp) {
    // ??? 
}

Enum stringToEnum(String inp) {
    // ???
}

Is there any way of doing this in dart? As far as i can tell you can do reflection with reflectable but I have not gotten this to work.

2

Answers


  1. enum ExampleEnum {
       first,
       second,
       third,
    }
    

    You can use enum.name property to convert enum to a String and back.

    //For Enum to a String:
    String enumToString(Enum inp) {
        return inp.name;
    }
    

    For converting String back to enum, you must ensure that the input must equals one of the enum.name or it will not work. You must also know the name of the list of enum here.

    Enum stringToEnum(String inp) {
        return ExampleEnum.values.firstWhere((e) => e.name == inp);
    }
    
    Login or Signup to reply.
  2. What I usually does to solve this is simply:

    1. Override the toString method of my enum.
    2. Create a static fromString method inside the enum.

    The code will look something like this:

    enum MyEnum {
      foo("foo"),
      bar("bar"),
      ;
    
      final String value;
      const MyEnum(this.value);
    
      /// This method returns the string value of the enum.
      @override
      String toString() => value;
    
      // This method creates the enum from String
      static MyEnum fromString(String str) {
        return values.firstWhere(
          (v) => v.value == str,
        );
      }
    }
    

    The usage would look like this:

    void main(List<String> args) {
      final en = MyEnum.foo;
    
      final strValue = en.toString();
    
      print(strValue); // > "foo"
    
      final backToEn = MyEnum.fromString(strValue);
    
      print(backToEn); // > foo (as MyEnum)
    }
    

    I find this is as a straight and concise way, since I’m not using a global method to handle the conversions, and all methods are abstracted into the particular enum class itself.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search