执行配置单元.openBox()时,生成的代码中出现强制转换错误



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

import 'dart:io';
import 'package:hive/hive.dart';
part 'hive_playground.g.dart';
@HiveType(typeId: 1)
class Person {
Person({required this.name, required this.age, required this.friend});
@HiveField(0)
String name;
@HiveField(1)
int age;
@HiveField(2)
Friend friend;
@override
String toString() {
return '$name: $age';
}
}
@HiveType(typeId: 2)
class Friend {
Friend({required this.friendName, required this.friendAge});
@HiveField(0)
String friendName;
@HiveField(1)
int friendAge;
}
void main() async {
var path = Directory.current.path;
Hive
..init(path)
..registerAdapter(PersonAdapter())
..registerAdapter(FriendAdapter());
var box = await Hive.openBox('testBox');
// var dave = Friend(friendName: 'Dave', friendAge: 22);
// var person = Person(name: 'Harry', age: 23, friend: dave);
// await box.put('Harry', person);
// print(box.get('Harry')); // Dave: 22
}

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

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

根据文档,FriendPerson类应该扩展HiveObject

因为旧的无效数据仍然存在于框中。

尝试:

Hive.deleteBoxFromDisk("accounts");
await Hive.openBox("accounts");

移除箱子。

最新更新