在Hive中检索数据



使用下面的代码将list存储到hive

@override
Future<void> saveProperty(List? propertyEntity) async {
try {
final invoiceBox = await Hive.openLazyBox(_propertyBox);
await invoiceBox.put('list', propertyEntity);
} on CacheException catch (e) {
throw CacheException(e.message);
}
}

检索时,使用get方法

@override
Future<List<PropertiesEntity>?> getPropertiesList() async {
try {
final propertiesBox = await Hive.openLazyBox(_propertyBox);
if (propertiesBox.isEmpty) return [];
var list = await propertiesBox.get('list');
if (list == null) return [];
return list.cast<PropertiesEntity>();
} on CacheException catch (e) {
throw CacheException(e.message);
}
}

但是如果我想获得一个特定的项目,为什么它会返回两个项目?我认为它应该只返回具有特定索引的项目?

@override
Future<PropertiesEntity?> getPropertyDetails() async {
try {
final propertiesBox = await Hive.openLazyBox(_propertyBox);
var propertyEntity = await propertiesBox.getAt(0); // this is the Listview's index
debugPrint(propertyEntity.toString());
} on CacheException catch (e) {
throw CacheException(e.message);
}
}

[Instance of 'PropertiesEntity', Instance of 'PropertiesEntity']

如果索引不够,则需要传递索引键

@override
Future<List<PropertiesEntity>?>  getPropertiesList() async {
try {
final propertiesBox = await Hive.openBox("data");
List<PropertiesEntity>? allData =propertiesBox.get("propertyList");
for(var j in allData!){
print(j.name);
}
return allData;
} catch (e) {
print("data==========$e");
}
}


@override
Future<PropertiesEntity?> getPropertyDetails(int index) async {
try {
final propertiesBox = await Hive.openBox("data");
List<PropertiesEntity>? allData =propertiesBox.get("propertyList");
print(allData!.length);
var propertyEntity = allData.elementAt(index);
print(propertyEntity.name);
return propertyEntity;
} catch (e) {
print("data==========$e");
}
}
@override
Future<void>saveProperty(List<PropertiesEntity> propertyEntity) async {
try {
final invoiceBox = await Hive.openBox("data");
await invoiceBox.put("propertyList", propertyEntity);
} catch (e) {
print(e.toString());
}
}

相关内容

  • 没有找到相关文章

最新更新