skip to Main Content

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


  1. You can use List.from to get list from map.

    final List<String> names =  List<String>.from(map['names'] as List);
    

    Make sure to get list while using map['names'].

    Login or Signup to reply.
  2. I think simplest solution is:

    List<String> channels = map['names']!.cast<String>();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search