Alex Kalmikov
Alex Kalmikov

Reputation: 2153

How to add an item of different type to List inside dynamic Map in Dart

Lets say I have a map:

Map map1 = {'a': ['x']};

When I try to add int item to list inside map -

map1['a'].insert(1, 77);

Error thrown:

type 'int' is not a subtype of type 'String' of 'element'

How can I resolve this?

Interesting that if same map was generated from JSON - above operation will succeed:

String json = '{"a": ["x"]}';
Map map2 = jsonDecode(json);

map2['a'].insert(1, 77);

// {a: [x, 77]}

EDIT: Defining strict type of map (reaching the type of List) not an option because it could be long nested map and its structure may vary. Also the type would be long and unreadable.

Upvotes: 2

Views: 549

Answers (1)

Zvi Karp
Zvi Karp

Reputation: 3904

dart assumes that the inner array is of type List<String>. therefor you should specify that the type is dynamic:

Map<String, List<dynamic>> map1 = {'a': ['x']};

or

Map map1 = {'a': <dynamic>['x']};

Upvotes: 2

Related Questions