isar / hive

Lightweight and blazing fast key-value database written in pure Dart.
Apache License 2.0
4.08k stars 404 forks source link

DateTime default value #974

Open TheCarpetMerchant opened 2 years ago

TheCarpetMerchant commented 2 years ago

I'd like to be able to specify DateTime(0) as a default value for DateTime objects. Of course you can't do this because DateTime(0) isn't const. A solution for this would be to specify true as the default value, which would actually generate DateTime(0) in the adapter.

One solution specifying true as the default value, which generates wrong code, but the error raised by the Dart compiler allows you to make the correction manually in the generated file. It's incredibly bad practice, I know. A better alternative is to have these fields be nullable, and use getters and setters. I don't like this approach because it adds unnecessary layers, but whatever works I guess.

Would it be possible to do this in a timely manner ? If not, I'll go with the nullable fields approach. It just annoys me because I'll then practically be stuck with these nullable fields and their accessors forever.

Thanks !

WasaLordy commented 1 year ago

I agree. A general solution would be great. Extending an existing Hive table is currently complicated. When adding a new HiveField which type is a new HiveType, I have to use this nullable approach, because I can not create a const constructor for a HiveObject.

Rexios80 commented 1 month ago

What's stopping you from doing this?

@HiveType(typeId: 6)
class ConstructorDefaults {
  ConstructorDefaults({
    DateTime? d,
  }) : d = d ?? DateTime.now();

  @HiveField(3)
  final DateTime d;
}
TheCarpetMerchant commented 2 weeks ago

What's stopping you from doing this?

@HiveType(typeId: 6)
class ConstructorDefaults {
  ConstructorDefaults({
    DateTime? d,
  }) : d = d ?? DateTime.now();

  @HiveField(3)
  final DateTime d;
}

Like other solutions, it adds different ways of doing the same thing. A good solution for sure compared to the others I proposed !

Rexios80 commented 2 weeks ago

As far as I know that's the only way to achieve a non-const default value. Annotations must be const.