isar / hive

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

Allow non-const default values #653

Open rubenvereecken opened 3 years ago

rubenvereecken commented 3 years ago

Is your feature request related to a problem? Please describe. We can now set default values. I think that's great, especially for when we introduce new non-nullable fields, so they're always guaranteed to have a value. The problem is that the default value needs to be a const expression. This means it can't be an instance of a subclass of HiveObjectMixin (which all of our non-primitive types are), because that doesn't have a const constructor.

Here's a simple example, say you have a new non-primitive field:

class NewComplexField with HiveObjectMixin {}

I would want to do:

class MyObject with HiveObjectMixin {
  @HiveField(14, defaultValue: NewComplexField())
  final NewComplexField complexField;
}

except that's not possible.

Describe the solution you'd like I think it be fixed by having a function generate default values. Something like

class MyObject with HiveObjectMixin {
  @HiveField(14, defaultValue: () => NewComplexField())
  final NewComplexField complexField;
}

Version

themisir commented 3 years ago

Unfortunately codegeneration for default values is limited by constant values. What you can do is you can write your own adapter to supply non-constant value.

HassanChamseddine commented 2 years ago

Unfortunately codegeneration for default values is limited by constant values. What you can do is you can write your own adapter to supply non-constant value.

Can you give an example of your suggestion? I am trying to do something like this too

class PatientData extends HiveObject {
  @HiveField(0,defaultValue:AccessToken())
  AccessToken? accessToken;

any further information on how I can support the non-constant value?

themisir commented 2 years ago

any further information on how I can support the non-constant value?

Not tested but you might try:

  1. Remove defaultValue use hive_generator to generate adapter for you.
  2. Copy contents of .g.dart file into separate file
  3. Modify read method to support custom substitute for null values
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;
}