hive icon indicating copy to clipboard operation
hive copied to clipboard

Update Specific Item in box based on criteria

Open deep1931 opened this issue 5 years ago • 3 comments

Hello,

I want to update a specific value in the box. Like I have contact list name,contact_number, image etc. I want to update the only image, based on contact_number can you please help to achieve this.

Regards

deep1931 avatar Apr 20 '20 11:04 deep1931

You can use the firstWhere method of the Iterable class to search through the records and find that specific contact you want to update. And if you extended the HiveObject in your contact model, it's even simplier to save the changes, you can even make it in a one liner like in the example below, but it's prone to fail if the contact isn't found, so you may consider putting some null-check mechanism before accessing to the record to prevent those errors.

var contacts = await Hive.openBox<Contact>('contacts');

contacts.values.firstWhere((contact) => contact.number == number)
        ..image = image
        ..save();

The re is no save method in my model. can you show me the save mehtod on your model ? thanks

congfandi avatar Apr 27 '22 01:04 congfandi

The re is no save method in my model. can you show me the save mehtod on your model ? thanks

If you've extended the "HiveObject" it should be accessible, it's implemented in hive_object.dart , if you're not using, then you can use box.put(key, value) to update