Hive:执行Hive.openBox()时生成的代码中出现强制转换错误

zf2sa74q  于 2022-09-27  发布在  Hive
关注(0)|答案(1)|浏览(159)

当我运行下面的代码时,打开框时会抛出一个_CastError。如果有帮助的话,我可以发布生成的代码,不过大概错误在我的源代码中。

  1. import 'dart:io';
  2. import 'package:hive/hive.dart';
  3. part 'hive_playground.g.dart';
  4. @HiveType(typeId: 1)
  5. class Person {
  6. Person({required this.name, required this.age, required this.friend});
  7. @HiveField(0)
  8. String name;
  9. @HiveField(1)
  10. int age;
  11. @HiveField(2)
  12. Friend friend;
  13. @override
  14. String toString() {
  15. return '$name: $age';
  16. }
  17. }
  18. @HiveType(typeId: 2)
  19. class Friend {
  20. Friend({required this.friendName, required this.friendAge});
  21. @HiveField(0)
  22. String friendName;
  23. @HiveField(1)
  24. int friendAge;
  25. }
  26. void main() async {
  27. var path = Directory.current.path;
  28. Hive
  29. ..init(path)
  30. ..registerAdapter(PersonAdapter())
  31. ..registerAdapter(FriendAdapter());
  32. var box = await Hive.openBox('testBox');
  33. // var dave = Friend(friendName: 'Dave', friendAge: 22);
  34. // var person = Person(name: 'Harry', age: 23, friend: dave);
  35. // await box.put('Harry', person);
  36. // print(box.get('Harry')); // Dave: 22
  37. }

这是试图打开盒子时抛出的错误消息。

  1. _CastError (type 'List<String>' is not a subtype of type 'Friend' in type cast)
vsaztqbk

vsaztqbk1#

根据文档,Friend和e1d1e类应该扩展HiveObject

相关问题