I get a json response from a server that looks like this:
{"status": "OK", "names": ["omegaChannel"]}
And then I parse it like this:
Map<String, dynamic> map = jsonDecode(response.body);
The ‘names’ field of this map is a list of strings, so I want to convert it to a list of strings:
List<String> channels = map['names'];
No problem at compile time, but when the app reaches this line at runtime, I get this error:
Error: Expected a value of type 'List<String>', but got one of type 'List<dynamic>
I have tried the following solutions but to no avail. They all get the error.
Using .map() and .toString():
List<String> channels = map['names'].map((val) => val.toString()).toList();
Casting to a list of strings:
List<String> channels = map['names'] as List<String>;
Or even just using a plain list first:
List channels4 = map['names'] as List<String>;
Thanks
2
Answers
You can use
List.from
to get list from map.Make sure to get list while using
map['names']
.I think simplest solution is: