首页 > 解决方案 > 如何在 Flutter 中发出 API 请求

问题描述

我是 Flutter 的新手,所以我不确定我应该如何进行 API 调用,来自我使用 Retrofit 的 Java。

JSON响应:

{
    "total": 13,
    "rows": [
        {
            "id": 1,
            "name": "Name"
        }
    ]
}

型号类:

class Category {
  int total;
  List<Rows> rows;
  Category({this.total, this.rows});

  Category.fromJson(Map<String, dynamic> json) {
    total = json['total'];
    if (json['rows'] != null) {
      rows = new List<Rows>();
      json['rows'].forEach((v) {
        rows.add(new Rows.fromJson(v));
      });
    }
  }
}
class Rows {
  String name;
  Rows({this.name});

  Rows.fromJson(Map<String, dynamic> json) {
    name = json['name'];
  }
}

主班

List<Rows> rows = [];


  Future<List<Rows>> getData() async {
    var response = await http.get(
        Uri.encodeFull("http://192.168.0.10/api/v1/categories"),
        headers: {
          "Authorization": "API",
          "Accept": "application/json"
        }
    );
    var jsonData = json.decode(response.body);
  }

我不知道如何处理我尝试使用 Rows.fromJson() 获取对象,但我只得到'Instance of Rows'并且通过调用名称我得到空值。

标签: jsonapiflutter

解决方案


该方法是正确的,但对于列表,您应该使用 list.map 来反序列化列表。

试试这个,我没有测试它,我只是看着你的例子写的

var response = await http.get(
    Uri.encodeFull("http://192.168.0.10/api/v1/categories"),
    headers: {
      "Authorization": "API",
      "Accept": "application/json"
    }
);
List<Rows> rows = [];

Map map = json.decode(response.body);
List l = map["rows"];
rows = l.map((map) => Rows.fromJson(map)).toList();

推荐阅读