繁体   English   中英

在 Flutter 中从 Node.js rest api 获取数据时出错(Mysql Localhost)

[英]Error while fetching data from Node.js rest api in Flutter ( Mysql Localhost)

错误:发生异常。 _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();

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM