【问题标题】:How to make an API request in Flutter如何在 Flutter 中发出 API 请求
【发布时间】:2020-01-14 07:53:14
【问题描述】:

我是 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',并且通过调用 name 我得到 null。

【问题讨论】:

    标签: json api flutter


    【解决方案1】:

    该方法是正确的,但对于列表,您应该使用 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();
    

    【讨论】:

    • 非常感谢,效果很好。你能给我解释一下这条线吗? rows = l.map((map) => Rows.fromJson(map)).toList();究竟是什么 => Rows.fromJson(map)).toList();
    • 这是因为json.decode(..)将json反序列化为Map对象,而json中的数组反序列化为List&lt;Map&gt;。当您访问map["rows"] 时,您会得到一个列表(隐式地图列表)。因此,您需要将列表中的所有地图转换为不同类型的对象。这是通过list.map(..) 函数完成的。使用 'map' 函数,列表中的每个对象都用于创建一个带有 Rows.fromJson(..) 的新对象
    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 2022-12-03
      • 2021-01-10
      • 2017-12-26
      • 1970-01-01
      • 2020-09-17
      • 2022-01-26
      • 2021-03-08
      • 2019-12-11
      • 2012-11-19
      相关资源
      最近更新 更多