flutter API请求
2020年7月14日 19:03
编程技术
dio 的使用
响应
虽然获取到的数据可以自动进行json解析,但是获取的数据不会自动进行类转换
即
dio.request<T>()
T 只能指定为 dynamic 或 Map,无法作为其他类进行转换,例如定义了一个类
@JsonSerializable()
class Site extends Object {
  String name;
  String version;
  String logo;
  int goods;
  int category;
  int brand;
  String currency;
  Site(this.name, this.version, this.logo, this.goods, this.category,
      this.brand, this.currency);
  factory Site.fromJson(Map<String, dynamic> json) => _$SiteFromJson(json);
  Map<String, dynamic> toJson() => _$SiteToJson(this);
}
而实际服务器响应的是json
{
"name": "zodream",
"version": "0.1",
"logo": "https://zodream.cn/assets/upload/image/wap_logo.png",
"category": 6,
"brand": 1,
"goods": 133,
"currency": "¥"
}
使用 dio.request<Site>() 是会报错的,
只能手动转换
var response = dio.request<Map<String, dynamic>>();
return Site.fromJson(response.data);