Search code examples
flutterenumsinternationalizationtranslation

Flutter enums i18n


I have a simple enum:

enum { TYPE_A, TYPE_B, TYPE_C ...}

My use case is to iterate over the enum values and print out translation of it.

Is there a way to do this with the standard i18n from Flutter?

Otherwise can someone recommend a plugin?


Solution

  • You can do it with slang:

    enum MyEnum {
      TYPE_A,
      TYPE_B,
      TYPE_C;
    
    String get label {
      switch (this) {
        case MyEnum.TYPE_A: return t.myEnum.typeA;
        case MyEnum.TYPE_B: return t.myEnum.typeB;
        case MyEnum.TYPE_C: return t.myEnum.typeC;
      }
    }
    

    The JSON would look like this:

    {
      "myEnum": {
        "typeA": "A",
        "typeB": "B",
        "typeC": "C"
      }
    }