我是 Dart 和 OOP 的新手。我正在使用冻结的包来创建我的模型类。我无法在我的函数中得到返回的响应,总是去 catch(error)
这是我的代码
static Future<SearchResponse?> searchImageBasedCatagory(
File file,
{requiresToken = true}) async {
try {
String fileExtension = p.extension(file.path);
List<String> finalExtension = fileExtension.split('.');
var formData = FormData.fromMap({
'searchImage': await MultipartFile.fromFile(
file.path,
contentType: MediaType("image", finalExtension[1]),
),
});
var res = await NetworkCommon.dio.post(
EndPoints.imageBasedSearch,
options: Options(
headers: {'requires_token': true},
),
data: formData,
);
var response = SearchResponse.fromJson(res.data);
return response;
} catch (error) {
return null;
}
}
我的模特
搜索回复
@freezed
class SearchResponse with _$SearchResponse {
factory SearchResponse({
required String message,
required int length,
required List<CameraImageCatagoryItem> data,
}) = _SearchResponse;
factory SearchResponse.fromJson( Map<String, dynamic> json) =>
_$SearchResponseFromJson(json);
}
相机图像类别项目
@freezed
class CameraImageCatagoryItem with _$CameraImageCatagoryItem {
factory CameraImageCatagoryItem(
{
int? width,
int? height,
required List<BoundBoxItem> boundBox}) = _CameraImageCatagoryItem;
factory CameraImageCatagoryItem.fromJson(Map<String, dynamic> json) =>
_$CameraImageCatagoryItemFromJson(json);
}
BoundBoxItem
@freezed
class BoundBoxItem with _$BoundBoxItem {
factory BoundBoxItem({
required String catagory,
int? prob,
int? area,
required List<int> bound_box,
List<int>? expand_by_bound_box,
required String gender
}) = _BoundBoxItem;
factory BoundBoxItem.fromJson(Map<String, dynamic> json) =>
_$BoundBoxItemFromJson(json);
}
数据样本
{
"message": "success",
"length": 1,
"data": [
{
"width": 299,
"height": 514,
"boundBox": [
{
"category": "t-shirts",
"prob": 0.9578810930252075,
"area": 0.5919081764116445,
"bound_box": [
25,
139,
299,
471
],
"expand_by_bound_box": [
0,
106,
298,
504
],
"gender": "men"
}
]
}
]
}
代码总是以错误块结束,消息总是 类型“Null”不是类型转换中类型“String”的子类型
这段代码有一些问题:
factory BoundBoxItem({
required String catagory,
int? prob,
int? area,
// ...
}) = _BoundBoxItem;
catagory
(第 4 个字母是“a”),但在数据 JSON 中它是 category
(第 4 个字母是“e”)。prob
和 area
提供 int
的类型,但在 JSON 中它是 double
。考虑使用 num
来处理 int
和 double
。