Flutter _TypeError(类型'List< dynamic>'不是类型'Map< String,dynamic>'的子类型) [英] Flutter _TypeError (type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>')
问题描述
我是陌生的,遇到类型错误。我正在尝试使用json自动序列化。
I am new to flutter and getting type error. I am trying to use json automated serializations.
在做一些表情之后,看起来像是这样
AFTER DOING SOME TWEAKS HERE IS HOW IT LOOKS LIKE
这是我尝试从api获取数据的方式
Here is how I am trying to get the data from 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);
}
有人可以帮我这个忙吗?我被困在这里。一直在尝试不同的方法,但没有任何效果。谢谢。
Could anyone please help me with this. I am stuck here. Have been trying different methods but none working. Thank you.
推荐答案
看来 data
是 List< dynamic>
,然后 data.map(someFunc).toList()
将把每个数据元素传递给 someFunc
并将其重新组成返回类型为 someFunc
的列表(您可能希望将其设为 BaseResponse
)。这告诉您 someFunc
必须是一个具有 dynamic
动态并返回 BaseResponse
。
It looks like data
is a List<dynamic>
, then data.map(someFunc).toList()
will take each element of data pass it to someFunc
and form it back into a list of the return type of someFunc
(which you will presumably want to be BaseResponse
). Which tells you that someFunc
needs to be a function that takes dynamic
and returns BaseResponse
.
您想写这样的东西:
final data = json.decode(res.body);
List<BaseResponse> responses =
data.map((j) => BaseResponse.fromJson(j)).toList();
这篇关于Flutter _TypeError(类型'List< dynamic>'不是类型'Map< String,dynamic>'的子类型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!