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.
class Hyperlink {
String url;
bool loaded;
String? img;
String? title;
String? desc;
String short;
Hyperlink({
required this.url,
this.loaded = false,
this.img,
this.title,
this.desc,
required this.short,
});
Hyperlink copyWith({
String? url,
bool? loaded,
String? img,
String? title,
String? desc,
String? short,
}) =>
Hyperlink(
url: url ?? this.url,
loaded: loaded ?? this.loaded,
img: img ?? this.img,
title: title ?? this.title,
desc: desc ?? this.desc,
short: short ?? this.short,
);
factory Hyperlink.fromMap(Map<String, dynamic> json) => Hyperlink(
url: json['url'],
loaded: json['loaded'],
img: json['img'],
title: json['title'],
desc: json['desc'],
short: json['short'],
);
factory Hyperlink.fromHive(Map<dynamic, dynamic> json) => Hyperlink(
url: json['url'],
loaded: json['loaded'],
img: json['img'],
title: json['title'],
desc: json['desc'],
short: json['short'],
);
Map<String, dynamic> toMap() {
return {
'url': url,
'loaded': loaded,
'img': img,
'title': title,
'desc': desc,
'short': short,
}..removeWhere(
(dynamic key, dynamic value) => key == null || value == null);
}
}
There I have a 2 factory method, which is just fromMap
and fromHive
and whenever I get data from Hive
I just use fromHive
In case of storing data, you can simply store a Map<String,dynamic>
to hive.
Hope this helps.
Thank you.