Home > Net >  How to convert enums to Map<int, String> in dart (Flutter)
How to convert enums to Map<int, String> in dart (Flutter)

Time:04-12

I have following enum definition:

enum ContentType {
  calendar,
  order,
  car,
  operator
}

in my code i want to call a function like this:

...

                DropDownSettingsTile(
                    title: "Column",
                    settingKey: SettingKeys.userColumnSelection,
                    selected: 0,
                    values: ContentType.values.asMap(),   // <---- Fails !!
                  onChange: (value){
                      print("setting change to: $value");
                  },
                ),
...

as mentioned above, I get a problem here, with following error: The argument type 'Map<int, ContentType>' can't be assigned to the parameter type 'Map<int, String>'.

I thought, in my simple mind, that values from enum sets was represented as Strings, but no...

...what is the best way to convert an enum mapped set from my <int, ContentType> to <int, String> ?

CodePudding user response:

You could write this for example

ContentType.values.map((e) => e.toString()).toList().asMap()

Though I doubt that is exactly what you want because the Strings will be in the form of "ContentType.calendar" for example. So maybe this is what you want:

ContentType.values.map((e) => e.toString().split(".")[1]).toList().asMap()
  • Related