flutter - 在使用 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'],
);
}
}
解决方案
我不知道您是否熟悉设计模式,但在这种情况下,您需要一个中间层,在数据库/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 模型之外,但这应该让您了解您可以做什么
推荐阅读
- ruby-on-rails - Use sidekiq to limit request through Net::http request
- hyperledger-fabric - 如何访问 IBM Private docker 存储库
- javascript - How to customize when merge an array in Javascript
- jquery - 解析:查询类属性并按邻近度排序
- c++ - What does the ampersand do here?
- javascript - How to fix addEventListener in my code? It seems like it's being canceled at any time
- python - Local variable have value '.!toplevel.!calendar.!frame' on VARIABLES section visual studio code when debugging python code
- javascript - My WordPress project on the live server is not enqueuing JS files (404 Error Recieved)
- python - Access a form method from generic.UpdateView in Django
- javascript - Three.js animated color change control