我目前正在构建一个应用程序。我已经收到了来自我调用的API的响应。只是当我想将响应保存到Hive框中时,出现了如下错误
我为UnitModel(unit_model.dart)创建了一个模型类:
// To parse this JSON data, do
//
// final unitModel = unitModelFromJson(jsonString);
import 'dart:convert';
UnitModel unitModelFromJson(String str) => UnitModel.fromJson(json.decode(str));
String unitModelToJson(UnitModel data) => json.encode(data.toJson());
class UnitModel {
bool status;
String msg;
List<UnitListDataModel> data;
UnitModel({
required this.status,
required this.msg,
required this.data,
});
factory UnitModel.fromJson(Map<String, dynamic> json) => UnitModel(
status: json["status"],
msg: json["msg"],
data: List<UnitListDataModel>.from(json["data"].map((x) => UnitListDataModel.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"msg": msg,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class UnitListDataModel {
int? id;
String? kodeUnit;
double? endMeter;
UnitListDataModel({
this.id,
this.kodeUnit,
this.endMeter,
});
factory UnitListDataModel.fromJson(Map<String, dynamic> json) => UnitListDataModel(
id: json["id"],
kodeUnit: json["kode_unit"],
endMeter: json["end_meter"],
);
Map<String, dynamic> toJson() => {
"id": id,
"kode_unit": kodeUnit,
"end_meter": endMeter,
};
}
字符串
这是meter_service.dart读取json
class MeterServices {
final _api = DioHelper().getDio();
final _prefs = Prefs();
Future<void> _addItem(List<Map<String, dynamic>> newItems) async {
for (var newItem in newItems) {
await _prefs.item.add(newItem);
}
}
Future<UnitListDataModel> getListUnit({String? kode}) async {
final res = await _api.post('/unit/get');
if (_prefs.item.isEmpty) {
// print("______________________");
// print(res.data);
// print("______________________");
_addItem(res.data['data']);
}
return UnitListDataModel.fromJson(res.data);
}
}
型
我如何克服这个错误,使数据可以存储在Hive盒,我提供.谢谢
1条答案
按热度按时间egmofgnx1#
您可以通过将其编码为
String
来保存整个JsonResponse
。当从HIVE中检索时,您可以使用jsonEncode和jsonDecode将其解码回Map。字符串