错误:发生异常。_TypeError(“List”类型不是“Map”类型的子类型)
Future<Album> fetchAlbum() async{
final response = await http.get(Uri.encodeFull("192.168.43.106:8080/customers/"),
headers: { "Accept": "application/json" } );
if (response.statusCode == 200) {
return Album.fromJson(json.decode(response.body));
}
else{
throw Exception('Failed to load Album');
}
}
class Album {
final int id;
final String email;
final String name;
Album({this.id, this.email, this.name});
factory Album.fromJson(Map<String, dynamic> json){
return Album(
id: json['id'],
email: json['email'],
name: json['name'],
);
}
}
您的响应是对象列表,而不是单个对象。因此,您必须传递列表的 [0] 索引。
试试下面的代码,它会为你工作。
Future<Album> fetchAlbum() async{
final response = await http.get(Uri.encodeFull("192.168.43.106:8080/customers/"),
headers: { "Accept": "application/json" } );
if (response.statusCode == 200) {
var str = jsonDecode(response.body);
return Album.fromJson(str[0]);
}
else{
throw Exception('Failed to load Album');
}
}
class Album {
int id;
String email;
String name;
Album({this.id, this.email, this.name});
Album.fromJson(json)
: id = json['id'],
email = json['email'].toString(),
name = json['name'].toString();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句