hive
hive copied to clipboard
Default value within the `HiveField` annotation
Hi!
Have an idea how the default values can be set in easy way for TypeAdapter
.
All we need - add new field to HiveField
annotation and then use it during class generation.
class HiveField {
final int index;
final dynamic defaultValue;
const HiveField(this.index, {this.defaultValue});
}
Then in our class we can do like this:
@HiveType()
class CityHive {
@HiveField(0, defaultValue: -1)
int id;
@HiveField(1, defaultValue: "Some name")
String name;
@HiveField(2)
double lat;
@HiveField(3)
double lng;
}
Generated class will looks like this:
class CityHiveAdapter extends TypeAdapter<CityHive> {
@override
CityHive read(BinaryReader reader) {
var numOfFields = reader.readByte();
var fields = <int, dynamic>{
for (var i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return CityHive()
..id = fields[0] as int ?? -1
..name = fields[1] as String ?? "Some name"
..lat = fields[2] as double
..lng = fields[3] as double
}
...
}