I'm looking to store a User object in a hive box. After a successful POST, I return a User object, which Hive won't add to a box because it's not the HiveType model that I wrote (HiveUser). Is there a way around this or can I convert my User object to the HiveUser object that I wrote specifically for adding a user to the box? Here is a few snippets to give an idea.
Where I call the function for the POST and get back the User Object
onPressed: () async {
User user;
try {
user = await loginUser(passwordController.text, nameController.text);
} on Exception {
print(Text("Exception has occurred during login"));
}
// print(nameController.text);
if(user.success) {
addUser(user);
Function that adds the User to the box. I need this to use the HiveUser object to successfully add it. But the User comes in as the plain User object from the POST response body.
void addUser(User user) {
// I need a HiveUser user here.
final userBox = Hive.box('user');
userBox.add(user);
}
User model that gets used initially.
class User {
bool success;
String userID;
String firstName;
String lastName;
User({this.success, this.userID, this.firstName, this.lastName});
factory User.fromJson(Map<String, dynamic> json) {
return User(
success: json['success'],
userID: json['UserID'],
firstName: json['FirstName'],
lastName: json['LastName'],
);
}
}
I don't know if you're familiar with design patterns but what you would need in this case would be a middle layer that do the transformation of your data between your database/API and your models (User and HiveUser) or a factory constructor that do it for you
for example a method like this
and in addUser
It would be better to have a middle layer to do that instead of modifying the model class (a DAO for example) to keep the logic outside the Hive model, but this should give you a glimpse of what you can do