I have a Hive box to save a Map<String, dynamic>
using toJson()
. But when I retrieve it, the result are a Map<dynamic, dynamic>
, I’ve tried converting it using jsonDecode()
, but not working. I also have tried converting it to String first then wrapping it up with jsonEncode()
then jsonDecode()
, still not working.
PS: Datatype other than a Map does work without problem
final HiveHelper hh = HiveHelper();
final box = Hive.openBox('boxip');
...
...
Future<void> saveDataIp(Map<String, dynamic> ip) async {
await hh.saveToBox(box, 'ip', ip);
}
...
Map<String, dynamic> getDataIp() {
Map<String, dynamic> map = {};
// ip resulting a _Map<dynamic, dynamic>
final ip = hh.getFrombox(box, 'ip');
if (ip != null) {
// with only using jsonDecode() gives error type "'_Map<dynamic, dynamic>' is not a subtype of type 'String'"
// below gives error "Converting object to an encodable object failed: Instance of 'DateTime'"
map = Map<String, dynamic>.from(jsonDecode(jsonEncode(ip)));
}
return map;
}
...
...
...
final data = Data(id: 1, name: "item", date: "2023-07-17T10:45:40.070Z");
await saveDataIp(data.toJson());
final dataBox = getDataIp();
2
Answers
First, here are 2 types to get a cleaner code and get less lost in your code:
I’m not sure to understand what is your problem.
If I summarise:
then what do you need to do? You can add a fromMap() method in your Data class to parse your box result back into Data type.
Also why don’t you use directly box.save() and box.get()?
data.dart:
Then:
And:
let me know if it answers your need