如何解决如何使用 Customer TypeAdapter (Hive/Flutter)?
我不太确定如何在 Flutter 中使用 Hive DB。我的意思是我有一个 ```WooCustomer```` 模型类,我想将它存储在本地(一旦客户登录)。
我的问题是,我必须将 WooCustomer
转换为 HiveObject
然后创建 TypeAdapter
还是直接创建 TypeAdapter<WooCustomer>
?
PS:WooCustomer 是一个外部包。
这是实现 TypeAdapter<WooCustomer>
的正确方法吗?
class DatabaseAdapterService extends TypeAdapter<WooCustomer> {
@override
final int typeId = 0;
@override
WooCustomer read(BinaryReader reader) {
return WooCustomer()
..id = reader.read()
..username = reader.read()
..firstName = reader.read()
..lastName = reader.read()
..email = reader.read()
..password = reader.read()
..avatarUrl = reader.read()
..role = reader.read()
..dateCreated = reader.read()
..dateCreatedGmt = reader.read()
..dateModified = reader.read()
..dateModifiedGmt = reader.read()
..isPayingCustomer = reader.read()
..links = reader.read()
..MetaData = reader.read()
..billing = reader.read()
..shipping = reader.read();
}
@override
void write(BinaryWriter writer,WooCustomer customer) {
writer.write(customer.username);
writer.write(customer.id);
writer.write(customer.firstName);
writer.write(customer.lastName);
writer.write(customer.email);
writer.write(customer.password);
writer.write(customer.links);
writer.write(customer.avatarUrl);
writer.write(customer.role);
writer.write(customer.MetaData);
writer.write(customer.dateCreated);
writer.write(customer.dateCreatedGmt);
writer.write(customer.dateModified);
writer.write(customer.dateModified);
writer.write(customer.dateModifiedGmt);
writer.write(customer.isPayingCustomer);
writer.write(customer.billing);
writer.write(customer.shipping);
}
}
解决方法
是的,你总是可以做到的。
首先在pubspec.yaml 的依赖项中获取这些插件hive,hive_flutter
。
并且在 pubspec 文件中还有一个 dev dependencies
部分添加,hive_generator: ^1.1.0 build_runner: ^2.0.1
你很高兴开始...... 首先以这种格式编写您的类,
import 'package:hive/hive.dart'; //import Hive
part 'weather_model.g.dart';
// Specify the Location of the type-adapter's Location (specifically)
//Add the .g.dart extension
// at last of the same File name you are using
// and add "part" keyword before all.
@HiveType(typeId: 0) //Add this Line
class WeatherModel {
@HiveField(0) //Add this Line,From Index 0... and so on.
String user_city; // Your Class Materials...
@HiveField(1) //Add this Line,From Index 0... and so on.
bool celciusMetric;
WeatherModel(
{this.user_city,this.celciusMetric}); //Constructor here..
// flutter packages pub run build_runner build
}
在您阅读完上面的全部注释代码后,
并根据您的用途实施。
转到您的终端并在那里写下,flutter packages pub run build_runner build --delete-conflicting-outputs
就可以了,您会发现
现在转到您的 main.dart
并导入 hive 的所有内容。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。