isar / isar/hive

How to delete the oldest entry in the box while using a custom key with put()

Open
#579 5 comments 1 reaction 0 assignees View on GitHub
question
Dominant language
Dart
Stars
4.4k
Forks
449
PR merge metrics
No merged PRs in 30d

Description

I have a box where I save a custom object, and I use put with a key. The problem is that I want to make the box max limit as 50, for example, when I add one, I want the oldest one to be deleted after it reaches 50. Is there a way to this? I was able to do this when I was saving with add with the incremental key, but I had to change use put and a key I generate.

```
/// Save past affirmations until 50 keys, then delete the first
Future savePastAffirmations(int index) async {
var affirmationBox = Hive.box(HiveBoxKey.pastAffirmations);
final Affirmation affirmation = todayAffirmations[index];

if (affirmationBox.containsKey(affirmation.key)) return;

if (affirmationBox.length > 50) {
//TODO delete oldest entry
}

if (!affirmationBox.containsKey(todayAffirmations.first.key)) {
await affirmationBox.put(
todayAffirmations.first.key, todayAffirmations.first);
}

await affirmationBox.put(affirmation.key, affirmation);

print("Past affirmations: ${affirmationBox.values}");
}
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.