hive
hive copied to clipboard
Avoid duplicating objects.
Question How to avoid duplicating objects in datastore? What is the best practice let Hive know that the object must be overridden or ignored instead of duplicating.
Code sample
Future
Future<List<CountryDataEntity>> getCountries() async { final List<CountryDataEntity> countries = <CountryDataEntity>[]; final Box<CountryDataEntity> box = await openDataBox(); countries.addAll(box.values.toList()); return countries; }
Version
- Platform: iOS, Android, Web
- Flutter version: [ 2.5.3]
- Hive version: [2.0.4]
### Tasks
- [ ] https://github.com/isar/hive/issues/1261
If you are retrieving new data from your API you can clear your box and add the new ones.
Future addCountries(List countries) async {
final box = await openDataBox();
await box.clear()
await box.addAll(countries);
}
If the data is not always new but you want to keep track of old data do:
Future addCountries(List countries) async {
final box = await openDataBox();
final existing = await getCountries(); // This returns the data you have already stored
final result = existing.addAll(countries).toSet(); // This removes duplicates
await box.addAll(result);
}