dart 如何使用公共基础HiveCacheOperation初始化两个不同的模型类?

qgelzfjb  于 5个月前  发布在  Hive
关注(0)|答案(1)|浏览(73)
final class HiveCacheManager extends CacheManager {
  /// [path] is the path to the directory
  ///  where the Hive database files are stored.
  HiveCacheManager({super.path});

  @override
  Future<void> init({required List<CacheModel> items}) async {
    final documentPath = path ?? (await getApplicationDocumentsDirectory()).path;
    Hive.defaultDirectory = documentPath;

    for (final item in items) {
      Hive.registerAdapter('${item.runtimeType}', item.fromDynamicJson);
    }
  }

  @override
  void remove() {
    Hive.deleteAllBoxesFromDisk();
  }
}

个字符
未处理异常:无效参数:类型不匹配。应为UserCacheModel,但获得了UserTokenCacheModel。E/flutter(11169):#0 _TypeRegistry.fromJson(package:hive/src/impl/type_registry.dart:45:7)E/flutter(11169):#1 _BoxImpl._frameFromJson(package:hive/src/impl/box_impl.dart:80:31)E/flutter(11169):#2 MappedListIterable.elementAt(dart:_internal/iterable.dart:425:31)E/flutter(11169):#3 ListIterator.moveNext(dart:_internal/iterable.dart:354:26)E/flutter(11169):#4 new _GrowableList._ofEfficientLengthIterable(dart:core-patch/growable_array.dart:189:27)E/flutter(11169):#5 new _GrowableList.of(dart:core-patch/growable_array.dart:150:28)E/flutter(11169):#6 new List.of(dart:core-patch/array_patch.dart:39:18)
我将使用两个不同的类模型,使用一个公共的基础Hive操作类。

yquaqz18

yquaqz181#

这不是正确的用法。

Hive.registerAdapter('${item.runtimeType}', item.fromDynamicJson);

字符串
正确的用法是=>

Hive.registerAdapter<AdapterClass>(AdapterClass());

相关问题