我是新手扑动并且出现类型错误。我正在尝试使用json自动序列化。
在这里做了一些事情后,它看起来如何
以下是我试图从api获取数据的方法
Future getMyProduct() async {
final res = await http.get('url');
final data = json.decode(res.body);
BaseResponse req = new BaseResponse.fromJson(data);
return req;
}
我的BaseResponse
课程看起来像这样
import 'package:dynamicapp/model/model.dart';
import 'package:json_annotation/json_annotation.dart';
part 'response.g.dart';
@JsonSerializable()
class BaseResponse extends Object {
final int id;
final int sellingPrice;
final int totalStock;
final String productName;
final String productDesc;
final List<Image> images;
BaseResponse(this.id, this.sellingPrice, this.totalStock, this.productName,
this.productDesc, this.images);
factory BaseResponse.fromJson(Map<String, dynamic> json) => _$BaseResponseFromJson(json);
Map<String, dynamic> toJson() => _$BaseResponseToJson(this);
}
@JsonSerializable()
class Image extends Object {
final int id;
final String image;
// final int product_id;
Image(this.id, this.image);
factory Image.fromJson(Map<String, dynamic> json) => _$ImageFromJson(json);
Map<String, dynamic> toJson() => _$ImageToJson(this);
}
有谁可以帮我这个。我被困在这里。一直尝试不同的方法但没有工作。谢谢。
它看起来像data
是一个List<dynamic>
,然后data.map(someFunc).toList()
将把每个数据元素传递给someFunc
并将其形成一个返回类型的someFunc
列表(你可能想要成为BaseResponse
)。这告诉你,someFunc
需要是一个功能,需要dynamic
并返回BaseResponse
。
你想写这样的东西:
final data = json.decode(res.body);
List<BaseResponse> responses =
data.map((j) => BaseResponse.fromJson(j)).toList();