在Hive中检索数据

kpbpu008  于 2023-04-06  发布在  Hive
关注(0)|答案(1)|浏览(160)

我使用下面的代码将列表存储到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']
hivapdat

hivapdat1#

在你的情况下索引是不够的你需要通过索引键

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

相关问题