flutterdartflutter-hive

Retrieve data in Hive


I storing list into hive using below code:

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

When retrieve, I use get method:

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

But if I want to get a specific item, why it will return two items? I thought it should return items with specific index only?

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

Output

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

Solution

  • in your case index is not enough you need to pass the index key

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