If you have an ID property on your object:
class Person{
int id;
String name;
Person({this.id,this.name});
}
and want to use the auto-increment functionality of the box.add() method you'd have to write on database twice:
var mario = Person(name: 'mario');
var key = await box.add(mario);
mario.id = key;
await box.put(key, mario);
but if we had a auto-increment API we could do something like:
var mario = Person(name: 'mario');
mario.id = box.getTheNextKey();
await box.put(mario.id, mario);
would something like this make sense for hive? is there already a way to get the auto-incremented key? I know we can generate our own key but I can't think of a way that's not more expensive than package's own implementation.
If you extend HiveObject, you get the key:
class Person extends HiveObject {
int id;
String name;
Person({this.id,this.name});
}
var mario = Person(name: 'mario');
box.add(mario);
await box.put(mario.key, mario);
It also allows you to do the following:
var mario = Person(name: 'mario');
box.add(mario);
mario.name = "somethingElse";
mario.save();
Does this already solve your problem?
Both of those Marios still don't have an ID property assigned. I know we could do something like mario.id = mario.key and in the end, we wouldn't even need an ID property if we already have a key but that's not allowed in the layered architecture my app has. my entities in the UI layer can't extend HiveObject because they shouldn't know I'm using Hive in my data layer. my models in the data layer do extend HiveObject but they can't communicate with UI using their key property.
in all of these approaches, we'd have to write on the box twice if we want to store the ID.
I guess we could do the mario.id = mario.key while reading the data from the box or put a getter on ID that returns the key and not store the ID in the database but IMO it would've been a lot more readable and less confusing if there was a public API for getting the auto-incremented key.
if you think this wouldn't make sense for Hive and is too specific, I guess I can use a forked Hive. just wanted to let you know of our use-case.
I think it would not hurt to create a public autoIncrement() method... I'll implement it for the next release.
Most helpful comment
I think it would not hurt to create a public
autoIncrement()method... I'll implement it for the next release.