A value of type 'List<dynamic>' can't be assigned to a variable of type 'List<String>'

Viewed 1192
Future<String> _loadCurrencies() async {
  String uri = "http://api.exchangeratesapi.io/latest?access_key=apikey";
  var response =
      await http.get(Uri.parse(uri), headers: {"Accept": "application/json"});
  var responseBody = json.decode(response.body);
  Map curMap = responseBody['rates'];
  currencies = curMap.keys.toList();
  setState(() {});
  print(currencies);
  return "Success";
}

It shows the error A value of type 'List<dynamic>' can't be assigned to a variable of type 'List<String>'.

At first, I tried the as Map but I can't seem to solve this error.

3 Answers

The problem

When you do

Map curMap = responseBody['rates'];
currencies = curMap.keys.toList();

curMap is a Map<dynamic, dynamic> and curMap.keys() is a Iterable<dynamic>. Since currencies is a List<String>, you can't assign it to curMap.keys().toList().

The solution

Just change it to

Map<String, dynamic> curMap = responseBody['rates'];
currencies = curMap.keys.toList();

If you are sure that it will have strings, you can do

currencies = curMap.keys.toList().cast<String>();

convert keys to string

currencies = curMap.keys.map(e => e.toString()).toList();
Related