【问题标题】:HiveError: There is already a TypeAdapterHiveError:已经有一个 TypeAdapter
【发布时间】:2021-03-04 17:29:21
【问题描述】:

我目前正在我的 FlutterApp 中实现 Hive。不幸的是,这个错误一直弹出:

HiveError: 已经有 typeId 100 的 TypeAdapter。

这是我的对象:

@HiveType(typeId: 100)
class ShopList{
  @HiveField(0)
  String name;
  @HiveField(1)
  List<ListProduct> products = List();

  ShopList({this.name, this.products});

这是自动生成的适配器:

class ShopListAdapter extends TypeAdapter<ShopList> {
  @override
  final int typeId = 100;

  @override
  ShopList read(BinaryReader reader) {
    final numOfFields = reader.readByte();
    final fields = <int, dynamic>{
      for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
    };
    return ShopList(
      name: fields[0] as String,
      products: (fields[1] as List)?.cast<ListProduct>(),
    );
  }

  @override
  void write(BinaryWriter writer, ShopList obj) {
    writer
      ..writeByte(2)
      ..writeByte(0)
      ..write(obj.name)
      ..writeByte(1)
      ..write(obj.products);
  }

  @override
  int get hashCode => typeId.hashCode;

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is ShopListAdapter &&
          runtimeType == other.runtimeType &&
          typeId == other.typeId;
}

我还有一些其他对象的 typeIds 101 和 102,它们会引发相同的错误。 Hive.registerAdapter(ShopListAdapter));try-catch-block 中运行。因此,如果适配器已经加载,代码可以继续运行,但是使用来自Hive 的值的FutureBuilder-Widget 加载无限长。 你有什么建议吗?

【问题讨论】:

  • 我遇到了同样的问题,因为这是我第一次使用hive,等待有人给出答案,谢谢
  • 同样的问题!

标签: flutter dart flutter-hive


【解决方案1】:

您需要检查 typeId,即使在同一个文件中,它们也应该与其他类模型不同且唯一。

@HiveType(typeId: 0)
class Module1 {}

@HiveType(typeId: 1)
class Module2 {}

一旦 typeId 改变了,那么

reinstall the app,
delete .g.dart generated file,
run command ---> flutter packages pub run build_runner build

【讨论】:

  • 虽然和上面一样,我运行这个命令来重新创建一个“.g.dart”文件。 flutter packages pub run build_runner build --delete-conflicting-outputs
  • 是的,--delete-conflicting-outputs,直到正常工作
猜你喜欢
  • 2022-07-21
  • 2020-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-25
  • 1970-01-01
  • 2017-08-21
相关资源
最近更新 更多