Eyal Kutz
Eyal Kutz

Reputation: 310

How to correctly do type conversions in dart

I'm building a flutter app that uses Dog API but I am failing to convert the type of a Map to Map<String, List<String>>

I have tried to use map.cast<String,List<String>>() but while not producing an error when I try to return the result (after specifing that the function returns a Map<<String,List<String>>>), when I run print(map.runtimeType); the output is CastMap<String, dynamic, String, List<String>> and not Map<<String,List<String>>>

Future<Map<String,List<String>>> getbreeds() async{
    var json=await http.get('https://dog.ceo/api/breeds/list/all');
    var linkedHashMap =Map.from(jsonDecode(json.body)) ;
    var map=linkedHashMap['message'].cast<String,List<String>>();
    print(map.runtimeType);
    return map;
  }

I expect the output of print(map.runtimeType); to be Map<<String,List<String>>> but instead, I get CastMap<String, dynamic, String, List<String>>

Upvotes: 0

Views: 2457

Answers (1)

Nate Bosch
Nate Bosch

Reputation: 10915

A CastMap<String, dynamic, String, List<String>> is a subtype of Map<String, List<String>> so that isn't a problem here. It's comparable to a situation where you specify a return type of num and the concrete value you return is an int.

The issue you're going to hit is that when you read a value from the map you'll have a List<dynamic> instead of a List<String>. You need to change the runtime types on the inner values as well.

var map = (linkedHashMap['message'] as Map).map((key, value) => MapEntry<String, List<String>>(key, List.from(value));

Upvotes: 2

Related Questions