Issue
I'm a Flutter language learner, new to this world,
{
"USDBRL":
{
"id": "...",
"name": "...",...
}
}
My Dolar Model:
class Dolar {
String param1;
String param2;
// Constructor
Dolar({
required this.param1,
required this.param2,
});
factory Dolar.fromJson(Map<String, dynamic> json) {
return Dolar(
param1: json['param1'],
param2: json['param2'],
);
}
}
I need to grab all "USDBRL" fields, but when I run the app I get "flutter: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' ".
I've tried searching for resolutions on the internet, but none of the alternatives I've tried have worked.
Solution
You have incorrectly cast the "USDBRL" as a List, when it is a Map.
Get rid of this line:
List<dynamic> body = json["USDBRL"];
and replace with this line:
Map<String, dynamic> body = json["USDBRL"];
That should resolve the casting error you are seeing.
To resolve the toList
error, you need to change how you are getting the Dolar
.
Dolar dolar = Dolar.fromJson(body);
This is because the "USDBRL" does not contain a list of items. It is one object with properties and values. I'm assuming that those values inside "USDBRL" are what you are wanting to use to configure the data in the Dolar object. So you just change it to be a single instance of Dolar
that gets it's data from the "USDBRL" Map.
The final code could look something like this:
Future<Dolar> getDolar() async {
try {
Response res = await get(Uri.parse(endPointUrl));
if (res.statusCode==200) {
final json = jsonDecode(res.body);
Dolar dolar = Dolar.fromJson(json["USDBRL"] as Map<String, dynamic>);
return dolar;
} else {
throw ("Can't access the Dolar API");
}
} catch (e) {
print(e);
rethrow;
}
}
Answered By - daddygames
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.