Steps to Reproduce
I have created TypeAdapter from this comment to use extended class.
Code sample
pet.dart
import 'package:hive/hive.dart';
class Pet extends Equatable {
@HiveField(0)
final String name;
@HiveField(1)
final int age;
Pet(this.name, this.age);
@override
List<Object> get props => [name, age];
}
dog.dart
import 'package:hive/hive.dart';
import 'pet.dart';
part 'dog.g.dart';
@HiveType(typeId: 1)
class Dog extends Pet {
Dog(String name, int age) : super(name, age);
}
dog.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'dog.dart';
// **************************************************************************
// TypeAdapterGenerator
// **************************************************************************
class DogAdapter extends TypeAdapter<Dog> {
@override
final typeId = 1;
@override
Dog read(BinaryReader reader) {
var numOfFields = reader.readByte();
var fields = <int, dynamic>{
for (var i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return Dog();
}
@override
void write(BinaryWriter writer, Dog obj) {
writer
..writeByte(2)
..writeByte(0)
..write(obj.name)
..writeByte(1)
..write(obj.age);
}
}
How you can see, there is an error in the constructor of Dog in TypeAdapter, arguments are missing.
Version
Unfortunately, only zero-argument constructors and constructors which use Initializing parameters (like "Pet(this.name, this.age)") can be used.
I just stumbled into this.
For others who see this: that just means that a base class has to be non-final, and either have no constructor or a constructor with no arguments.
I do like my finals, but not too bad.
my problem is that I am using JsonSerializable for my classes and if I not specify the constructor, I will get
The class `Pet` has no default constructor.
so I have to use constructor for that.
any help is appreciated.
is there any way to fix the constructor issue ?
If you don't specify a constructor, then there's an implicit default constructor. Can you paste your class?
If you don't specify a constructor, then there's an implicit default constructor. Can you paste your class?
https://github.com/hivedb/hive/issues/442#issuecomment-720373939
Duplicate of #442
Most helpful comment
Unfortunately, only zero-argument constructors and constructors which use Initializing parameters (like "Pet(this.name, this.age)") can be used.