Reputation: 23
I have this class(dart)
class ResumenPublicaciones {
String name;
String count;
ResumenPublicaciones({this.name, this.count});
// named constructor
ResumenPublicaciones.fromJson(Map<String, dynamic> json)
: name = json['name'],
count = json['count'].toString();
}
I want to map this response from the API
[{"name":"Administración","count":37},{"name":"Call Center,
Teletrabajo y Telemarketing","count":4},{"name":"Compras,
Importaciones, Logística, Distribución","count":10}]
this is how Im doing it....
class ServicioResumenEmpleos {
List<ResumenPublicaciones> publicaciones = [];
List getResumenPublicacioness() {
publicacionesResumidas();
return publicaciones;
}
var apiUrl = "here my api URLs";
Future<ResumenPublicaciones> publicacionesResumidas() async {
var jsonResponse;
Map<String, String> headers = {
'Content-Type': 'application/json',
};
var response = await http.get(apiUrl, headers: headers);
print('respuesta del api' + response.toString());
if (response.statusCode == 200) {
print(' el API responde ' + response.body);
jsonResponse = json.decode(response.body);
var _listapublicaciones = new ResumenPublicaciones.fromJson(jsonResponse);
publicaciones.add(_listapublicaciones);
print(_listapublicaciones.name);
return _listapublicaciones;
} else {
print(
'Esta imprimiendo el else en este punto no debe impremir el response');
var _listapublicacionesNull = new ResumenPublicaciones();
_listapublicacionesNull.count = '0';
_listapublicacionesNull.name = 'didnt work';
return _listapublicacionesNull;
}
}
//
}
I want to receive a list on the class but im receiving this error msg
Exception has occurred.
**_TypeError (type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>')**
any Idea of what im doing wrong?
Upvotes: 0
Views: 42
Reputation: 24671
The problem is here:
var _listapublicaciones = new ResumenPublicaciones.fromJson(jsonResponse);
If your response is a list, you are passing it to a constructor that is expecting a Map
. You need to iterate over the objects of your list and convert them into individual publicaciones:
var _listapublicaciones = (jsonResponse as List).map(
(o) => ResumenPublicaciones.fromJson(o),
).toList();
Upvotes: 1