In flutter using Hive how would you add a custom object from a POST response body to a box?

1.3k views Asked by At

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'],

    );
  }
}
1

There are 1 answers

5
EdwynZN On

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

@HiveType(typeId: 0)
class HiveUser{
  @HiveField(0)
  String name;

  @HiveField(1)
  String lastName;

  @HiveField(2)
  int age;

  @HiveField(3)
  String gender;

  HiveUser({this.name, this.lastName, this.gender, this.age});

  //just like you would decode a json into a model
  factory HiveUser.fromUser(User user){
     return HiveUser(
        name: user.name
        lastName: user.lastName
        gender: user.gender,
        age: user.age
     );
  }
}

and in addUser

void addUser(User user) {
  // I need a HiveUser user here.
  final userBox = Hive.box('user');
  userBox.add(HiveUser.fromUser(user));
}

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