【问题标题】:Error while fetching data from Node.js rest api in Flutter ( Mysql Localhost)从 Flutter 中的 Node.js rest api 获取数据时出错(Mysql 本地主机)
【发布时间】:2020-07-09 18:50:36
【问题描述】:

错误:发生异常。 _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'],
  );
}

}

enter image description here

【问题讨论】:

  • 在这里放一些你尝试过的代码而不是图片,并显示实际错误是什么
  • Future 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'); } }
  • 你能分享专辑模型代码以及来自 api 的响应吗?
  • @MuhammadNoman 以上是更新的代码。请帮忙

标签: mysql node.js api flutter


【解决方案1】:

您的响应是对象列表,而不是单个对象。因此,您必须传递列表的 [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();

}

【讨论】:

    猜你喜欢
    • 2021-06-19
    • 2017-02-18
    • 2014-04-02
    • 2018-03-11
    • 2019-07-25
    • 2019-08-26
    • 1970-01-01
    • 2017-09-15
    相关资源
    最近更新 更多