Home > OS >  Why should I explicitly cast my JASON object as a Map<String, dynamic> in Dart?
Why should I explicitly cast my JASON object as a Map<String, dynamic> in Dart?

Time:02-12

If the dart convert package returns a json object, is there any advantage or necessity to casting the converted json to a Map<String, dynamic>? In the code below, I'm taking the response from an api and passing it to a factory that returns a Dart Place object. I'm trying to understand the benefit of casting the json as a map versus passing the result as a json object. Thanks for any insights.

var parsedJason = convert.jsonDecode(response.body);
var resultObj = parsedJason['result'] as Map<String, dynamic>; 
return Place.fromJson(resultObj);

CodePudding user response:

As we know, the JSON result for REST API gets outputted as a Map of key: value pairs where the key is always a String and the value can be of any type i.e. dynamic in Dart.

Casting the result as Map<String, dynamic> makes sure that the resultObj variable passed as a parameter in the fromJson() method is of the correct type accepted by the method, thus making the query error prone.

  • Related