我正在尝试使用Dio Client进行API调用。当我收到响应时,它将引发错误
'_ InternalLinkedHashMap'不是'String'类型的子类型
试图解决它,但我不能。下面是代码
Future<dynamic> get(
String uri, {
Map<String, dynamic> queryParameters,
Options options,
CancelToken cancelToken,
ProgressCallback onReceiveProgress,
}) async {
try {
final Response response = await _dio.get(
uri,
queryParameters: queryParameters,
options: options,
cancelToken: cancelToken,
onReceiveProgress: onReceiveProgress,
);
return response.data;
} catch (e) {
print(e.toString());
throw e;
}
}
}
发布Api呼叫
Future<News> getPosts() async {
try {
final res = await _dioClient.get(Endpoints.getPosts);
return News.fromJson(res);
} catch (e) {
print(e.toString());
throw e;
}
}
模型类使用built_value
abstract class News implements Built<News, NewsBuilder> {
News._();
factory News([updates(NewsBuilder b)]) = _$News;
@BuiltValueField(wireName: 'status')
String get status;
@BuiltValueField(wireName: 'totalResults')
int get totalResults;
@BuiltValueField(wireName: 'articles')
BuiltList<Articles> get articles;
String toJson() {
return json.encode(serializers.serializeWith(News.serializer, this));
}
static News fromJson(String jsonString) {
return serializers.deserializeWith(
News.serializer, json.decode(jsonString));
}
static Serializer<News> get serializer => _$newsSerializer;
}
序列化器类
@SerializersFor([
News,
Articles,
Source,
])
final Serializers serializers = (_$serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build();
帮助我解决问题
答案 0 :(得分:0)
您需要更改2件事
1)在build_value中使用jsonSerializers而不是默认的序列化器。
2)使用response.toString()代替dio中的数据。这是我的一个有效示例,只需复制所需的部分即可。
内置价值模型
abstract class TravelRequest implements Built<TravelRequest, TravelRequestBuilder> {
TravelRequest._();
factory TravelRequest([updates(TravelRequestBuilder b)]) = _$TravelRequest;
@nullable
@BuiltValueField(wireName: 'id')
int get id;
@nullable
@BuiltValueField(wireName: 'country_from')
String get countryFrom;
@nullable
@BuiltValueField(wireName: 'traveler_name')
String get travelerName;
@nullable
@BuiltValueField(wireName: 'traveler_email')
String get travelerEmail;
@nullable
@BuiltValueField(wireName: 'description')
String get description;
String toJson() {
return json.encode(jsonSerializers.serializeWith(TravelRequest.serializer, this));
}
static TravelRequest fromJson(String jsonString) {
return jsonSerializers.deserializeWith(TravelRequest.serializer, json.decode(jsonString));
}
static Serializer<TravelRequest> get serializer => _$travelRequestSerializer;
}
如何与Dio一起使用
Future createTravelRequest(TravelRequest travelRequest) {
return _apiProvider.dio.post(rootPath, data: travelRequest.toJson()).then((response) {
travelRequests.add(TravelRequest.fromJson(response.toString()));
});
}