flutter API请求

Fork Me On Github

dio 的使用

响应

虽然获取到的数据可以自动进行json解析,但是获取的数据不会自动进行类转换

dart
  
dio.request<T>()
12

T 只能指定为 dynamicMap,无法作为其他类进行转换,例如定义了一个类

dart
                 
@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);
}
1234567891011121314151617

而实际服务器响应的是json

json
         
{
"name": "zodream",
"version": "0.1",
"logo": "https://zodream.cn/assets/upload/image/wap_logo.png",
"category": 6,
"brand": 1,
"goods": 133,
"currency": "¥"
}
123456789

使用 dio.request<Site>() 是会报错的,

只能手动转换

dart
   
var response = dio.request<Map<String, dynamic>>();

return Site.fromJson(response.data);
123
点击查看全文
0 137 0