我有一个通过模型类从 api 获取的 itemlist,现在我想将该列表保存到 hive 中,并添加一些其他属性,如客户名称、客户地址和 itemsList。
import 'package:hive/hive.dart';
导入'.../item_model.dart';
导入'hive_model.dart';
part 'saved_hive_model.g.dart';
@HiveType(typeId: 15)
类 SavedDatInHive {
@HiveField(10)
final String totalPrice;
@HiveField(11)
final List<ItemList> list;
@HiveField(12)
final String CustomerName;
SavedDatInHive(this.list, this.CustomerName, {required this.totalPrice});}
</pre
import 'package:hive/hive.dart';
import 'item_model.dart';
part 'saved_hive_model.g.dart';
@HiveType(typeId: 15)
class SavedDataInHive { // 注意:类名已更正为 SavedDataInHive
@HiveField(10)
final String totalPrice;
@HiveField(11)
final List<ItemModel> list; // 使用 ItemModel 类型
@HiveField(12)
final String customerName; // 注意:变量名已更正为 customerName
@HiveField(13)
final String customerAddress; // 新增 customerAddress 属性
SavedDataInHive({
required this.totalPrice,
required this.list,
required this.customerName,
required this.customerAddress,
});
}
// 保存数据到 Hive
Future<void> saveDataToHive(List<ItemModel> items, String customerName, String customerAddress, String totalPrice) async {
// 初始化 Hive
await Hive.initFlutter();
// 注册 adapter
Hive.registerAdapter(SavedDataInHiveAdapter());
Hive.registerAdapter(ItemModelAdapter()); // 注册 ItemModel 的 adapter
// 打开 Hive box
var box = await Hive.openBox('myBox');
// 创建 SavedDataInHive 对象
var savedData = SavedDataInHive(
totalPrice: totalPrice,
list: items,
customerName: customerName,
customerAddress: customerAddress,
);
// 将数据添加到 Hive
await box.add(savedData);
}
// 从 Hive 读取数据
Future<List<SavedDataInHive>> loadDataFromHive() async {
// 初始化 Hive
await Hive.initFlutter();
// 注册 adapter
Hive.registerAdapter(SavedDataInHiveAdapter());
Hive.registerAdapter(ItemModelAdapter());
// 打开 Hive box
var box = await Hive.openBox('myBox');
// 获取所有数据
List<SavedDataInHive> savedDataList = [];
for (int i = 0; i < box.length; i++) {
savedDataList.add(box.getAt(i));
}
return savedDataList;
}
解释:
- 数据模型 :
-
将
SavedDataInHive
类名修改为更准确的名称。 -
将
list
的类型改为List<ItemModel>
,以正确存储ItemModel
对象列表。 -
将
CustomerName
更正为customerName
,以遵循驼峰命名法。 -
添加了
customerAddress
属性来存储客户地址。 -
保存数据 :
-
saveDataToHive
函数现在接受items
,customerName
,customerAddress
和totalPrice
作为参数。 -
使用
Hive.registerAdapter
注册ItemModelAdapter
,确保 Hive 可以正确存储和读取ItemModel
对象。 -
创建一个
SavedDataInHive
对象,并将所有数据传递给其构造函数。 -
使用
box.add(savedData)
将数据添加到 Hive。 -
读取数据 :
-
loadDataFromHive
函数从 Hive 中读取所有SavedDataInHive
对象,并将其作为列表返回。
使用示例:
// 假设你已经从 API 获取了 itemlist,customerName,customerAddress 和 totalPrice
// 保存数据
await saveDataToHive(itemlist, customerName, customerAddress, totalPrice);
// 读取数据
List<SavedDataInHive> savedDataList = await loadDataFromHive();
// 打印第一个保存数据的客户姓名
print(savedDataList[0].customerName);
请注意:
-
你需要为
ItemModel
类创建HiveObject
和TypeAdapter
。可以参考 Hive 文档中的说明进行操作:https://docs.hivedb.dev/#/basics/adapters -
你需要在
pubspec.yaml
文件中添加hive
和hive_generator
依赖项,并运行flutter packages get
命令。