Error: List is not a subtype of type Map

CodeWithFlutter
1 Min Read

This error message occurs when you are trying to assign a value of type List<dynamic> to a variable that expects a value of type Map<String, dynamic>.

In Dart, maps are key-value pairs, where each key is of type String and each value can be of any type, including dynamic. On the other hand, lists are simply collections of elements of any type, including dynamic.

To resolve this error, you need to convert the List<dynamic> value into a Map<String, dynamic> value. This can be done using the Map.fromIterable method, which creates a map from a list of key-value pairs. Here’s an example:

List<dynamic> list = [
  {"key": "value1"},
  {"key": "value2"},
];

Map<String, dynamic> map = Map.fromIterable(list,
    key: (item) => "key", value: (item) => item["key"]);

In this example, the Map.fromIterable method creates a map from the list where the keys are obtained using the key function and the values are obtained using the value function. The resulting map will be of type Map<String, dynamic>.

Share this Article
Leave a comment