I am caching a big chunk of data from API, I get it as a dynamic list which contains Map<String, dynamic>
.
I can either save the dynamic list itself which I get in response or else I can save the parsed object but
the object’s class is nested and has many types of objects, so adding adapters to all of the custom objects is cumbersome to manage.
Is there any better way to do this?
I tried storing the list directly but it only runs when the cache is fresh, after a restart the type data is lost and I get an error:
Unhandled Exception: type ‘_InternalLinkedHashMap<dynamic, dynamic>’ is not a subtype of type ‘Map<String, dynamic>’ in type cast
I referred to https://github.com/hivedb/hive/issues/522 but it didn’t solve my issue.
2
Answers
I solved it by saving my data as Json string instead of saving the data with their types. I used jsonEncode(data) and then while fetching it used jsonDecode(data).
TL;DR Create another factory method for fetching data from Hive.
Because of that issue, I actually include one factory method for Hive in the model class. For example, below is my
HyperLink
model class for preview information of a website.There I have a 2 factory method, which is just
fromMap
andfromHive
and whenever I get data fromHive
I just usefromHive
In case of storing data, you can simply store a
Map<String,dynamic>
to hive.Hope this helps.
Thank you.