Roar Grønmo
Roar Grønmo

Reputation: 3966

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

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> ?

Upvotes: 0

Views: 1397

Answers (1)

Ivo
Ivo

Reputation: 23179

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()

EDIT:
as jamesdlin pointed out, you can also just write

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

Upvotes: 2

Related Questions