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.
CodePudding user response:
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;
}
}
CodePudding user response:
Can you try this query. You need to define your class with 'as'.
final Map<String, dynamic> jsonResult = jsonDecode(response.body);
List<Dolar> dolar = (jsonResult['USDBRL']
as List<dynamic>)
.map((data) => Dolar.fromJson(data))
.toList();
And fromJson should like this.
factory Dolar.fromJson(Map<String, dynamic> json) {
return Dolar(
param1: json['id'],
param2: json['name'],
);
}