hive icon indicating copy to clipboard operation
hive copied to clipboard

Allow non-const default values

Open rubenvereecken opened this issue 4 years ago • 4 comments

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

  • Platform: iOS, Android, Mac, Windows, Linux, Web
  • Flutter version: 2.0.6
  • Hive version: 2.0.4

rubenvereecken avatar May 02 '21 17:05 rubenvereecken

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.

themisir avatar May 02 '21 17:05 themisir

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?

HassanChamseddine avatar Apr 14 '22 15:04 HassanChamseddine

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

themisir avatar Apr 14 '22 19:04 themisir