Reputation: 469
I want to populate a Map programatically but i don't know how to do that. Also i need that tagname
to be constant.
I made manually this, but if you have a thousand of Tag values, you have to write a thousand of lines of code:
enum Tag { tag1, tag2, tag3, tag4, tag5 }
Map<Tag, String> tagname = {
Tag.values[0]: 'Tag 1',
Tag.values[1]: 'Tag 2',
Tag.values[2]: 'Tag 3',
Tag.values[3]: 'Tag 4',
Tag.values[4]: 'Tag 5',
};
I want to populate tagname
with:
const List<String> tagtitles = ['Tag 1', 'Tag 2', 'Tag 3', 'Tag 4'];
and if tagtitles.lenght
< Tag.values.lenght
then populate with 'empty' String.
Can you help me? Thanks.
Upvotes: 2
Views: 6830
Reputation: 71713
The shortest way would probably be:
var tagName = {for (var tag in Tag.values)
tag: (tag.index < tagTitles.length ? tagTitles[tag.index] : "empty")};
It still cannot be constant.
Upvotes: 1
Reputation: 101
If you assume that the tagTitles and the Tag enum have the same order of items, you can do the following:
enum Tag { tag1, tag2, tag3, tag4 }
const List<String> tagTitles = ['Tag 1', 'Tag 2', 'Tag 3'];
Map<Tag, String> tagName = Map();
Tag.values.asMap().forEach((index, tag) =>
tagName[tag] = index < tagTitles.length ? tagTitles[index] : 'empty');
The map will look something like this
{Tag.tag1: Tag 1, Tag.tag2: Tag 2, Tag.tag3: Tag 3, Tag.tag4: empty}
And you can use tagName[Tag.tag1]
to access a item in the map.
Upvotes: 4