How to handle enum in Hive Flutter?
Asked Answered
B

1

11

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?

Bachelor answered 9/1, 2023 at 13:48 Comment(3)
Hi @rahulVFlutterAndroid yes eager to know please shareBachelor
are you still need it?Relish
I had am enum field saved without any additional effort within the class nine months ago. And now it requires an additional adapter... Thinking to use int or string property for storage and additional wrapper property as an enum representation. However Dominic's second advise is fine too.Phycomycete
M
16

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 {
  @HiveField(0)
  final String id;

  @HiveField(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);
}
Meanwhile answered 9/1, 2023 at 14:15 Comment(1)
Just a quick fix, your id and your Foo object in MyRepresentation should be annotated with HiveField and not HiveType.Acotyledon

© 2022 - 2024 — McMap. All rights reserved.