如何在 Hive Flutter 中处理枚举?

hri*_*ade 9 casting dart flutter flutter-hive

我的模型类中有一个枚举:

MyRepresentation { list, tabs, single }
Run Code Online (Sandbox Code Playgroud)

我已经添加了一个适配器并注册了它。我已经给它一个正确的类型 ID 和字段。

它给出错误:

HiveError:无法写入,未知类型:MyRepresentation。您是否忘记注册适配器?

Dom*_*nic 14

您也注册了枚举还是仅注册了模型?假设您的模型文件myrepresentation.dart如下所示:

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,
}
Run Code Online (Sandbox Code Playgroud)

然后生成类型适配器并在 main 中初始化它们

void main() async {
  await Hive.initFlutter();
  ...
  Hive.registerAdapter(MyRepresentationAdapter());
  Hive.registerAdapter(FooAdapter());

  runApp(MyApp());
}
Run Code Online (Sandbox Code Playgroud)

如果您已完成此操作但仍然遇到问题,您可以尝试将枚举放入其自己的文件中并编写自己的part语句。

如果这仍然不起作用,我建议您简单地将枚举存储为 int 自己在TypeAdapter read()write()方法中,如下所示:

@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);
}
Run Code Online (Sandbox Code Playgroud)