I have an enum in my model class: MyRepresentation { list, tabs, single } I have already added an adapter and registered it. I have given it a proper type id and fields.
It gives error : HiveError: Cannot write, unknown type: MyRepresentation. Did you forget to register an adapter?
CodePudding user response:
Did you register the enum too or just the model? Say your model file myrepresentation.dart looks like this:
import 'package:hive/hive.dart';
part 'myrepresentation.g.dart';
@HiveType(typeId: 1)
class MyRepresentation extends HiveObject {
@HiveType(0)
final String id;
@HiveType(1)
final Foo foo;
MyRepresentation({required this.id, required this.foo});
}
@HiveType(typeId: 2)
enum Foo {
@HiveField(0)
foo,
@HiveField(1)
bar,
}
Then you generate you type adapters and initialize both of them in your main:
void main() async {
await Hive.initFlutter();
...
Hive.registerAdapter(MyRepresentationAdapter());
Hive.registerAdapter(FooAdapter());
runApp(MyApp());
}
If you have done this and it is still giving you problems, you could try to put the enum in its own file and write its own part
statement.
If this still isn't working I suggest simply storing the enum as int yourself in the TypeAdapter
read()
and write()
methods like this:
@override
MyRepresentation read(BinaryReader reader) {
return MyRepresentation(
reader.read() as String,
Foo.values[reader.read() as int]
);
}
@override
void write(BinaryWriter writer, MyRepresentation obj) {
writer.write(obj.id);
writer.write(obj.foo.index);
}