首页 > 解决方案 > 在使用 Hive 进行颤振时,您如何将自定义对象从 POST 响应正文添加到框?

问题描述

我正在寻找将用户对象存储在蜂巢箱中。POST 成功后,我返回一个 User 对象,Hive 不会将其添加到框中,因为它不是我编写的 HiveType 模型 (HiveUser)。有没有办法解决这个问题,或者我可以将我的用户对象转换为我专门为将用户添加到框中而编写的 HiveUser 对象?这里有一些片段可以给出一个想法。

我在哪里调用 POST 函数并取回用户对象

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);

将用户添加到框中的函数。我需要这个来使用 HiveUser 对象来成功添加它。但是用户作为来自 POST 响应正文的普通用户对象进来。

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

最初使用的用户模型。

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

    );
  }
}

标签: flutterflutter-hive

解决方案


我不知道您是否熟悉设计模式,但在这种情况下,您需要一个中间层,在数据库/API 和模型(用户和 HiveUser)或工厂构造函数之间转换数据为你做的

例如这样的方法

@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
     );
  }
}

并在 addUser

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

最好有一个中间层来执行此操作,而不是修改模型类(例如 DAO)以将逻辑保留在 Hive 模型之外,但这应该让您了解您可以做什么


推荐阅读