Hive: Does inheritance work in Hive?

Created on 23 Sep 2020  路  9Comments  路  Source: hivedb/hive

Question
I have following base class which I need to store and class which extends it. Hive generator doesn't include fields of parent class in read method. Base Class g file generated correctly
Code of base class:

@HiveType(typeId: 4)
class BaseClass {
  @HiveField(0)
  final ...
  @HiveField(1)
  final ...
  @HiveField(2)
  final ...
  @HiveField(3)
  final ...
  @HiveField(4)
  final ...
  @HiveField(5)
  final ...
  @HiveField(6)
  final ...
  BaseClass (
    this....,
    this....,
    this....,
    this....,
    this....,
    this....,
    this....,
  );
}

Code of child class:

@HiveType(typeId: 6)
class ChildClass extends BaseClass{
///fields which extend base class
  @HiveField(7)
  final ...;
  @HiveField(8)
  final ...;
  @HiveField(9)
  final ...;

  ChildClass(
//field of base class
    ...,
    ...,
//fields of child class
    this.....,
    this.....,
    this.....,
  ) : super(....);//fields of base class
@override
  ChildClass read(BinaryReader reader) {
    final numOfFields = reader.readByte();
    final fields = <int, dynamic>{
      for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
    };
    return FullSprint(
//why only child fields????
      fields[7] as String,
      fields[8] as String,
      fields[9] as String,
    );
  }

Version

  • Platform: iOS, Android, Mac, Windows, Linux, Web
  • Flutter version: 1.20.0
  • Hive version: ^1.4.0
question

Most helpful comment

Inheritance support added in [email protected].

All 9 comments

Any updates over the matter?

Any updates over the matter?

You have same issue?

Yes exactly the same example, the parent members are never included in the generated constructor. I always end up adding them manually.

Currently hive_generator doesn't support class inheritance.

Ah, sorry I was under the influence that it does. However, how is this example different from the following resolved issue #70 ? I thought this feature was added based on this comment [ [The newest version of Hive and hive_generator support inheritance.](https://github.com/hivedb/hive/issues/70#issuecomment-568267176) ]

any help about what to do ?

any help about what to do ?

for now my algorithm for this issue:
1) generate classes as usually
2) remove hivetype annotations
3) replace suffix g.dart to something like _adapter.dart
4) after 2 and 3 if you run generator it won't do anything with your generated classes from 1
5) resolve issues of generator manually in your adapter

Inheritance support added in [email protected].

Thanks a ton for allowing non initializingFormal constructor parameters, some time ago i had an class misteriously failing the non null param assertions after being stored and fetched.

Was this page helpful?
0 / 5 - 0 ratings