如何解决保存 hive flutter 中的对象列表
我想在 Flutter hive 中保存对象列表。有什么方法可以实现它。我为笔记创建了一个模型类。它具有注释标题和描述字段。我想使用 DateTime.Now() 作为 Key 将 List 保存在 hive Flutter 中。有什么办法可以实现吗?
class NotedBox {
static Box<List<NotesModel>> getNotedBox() {
return Hive.Box<List<NotesModel>>("Notes");
}
}
这是我在 main.dart 中打开的盒子。
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
Directory appDocDir = await getApplicationDocumentsDirectory();
Prefrences.init();
await Hive.initFlutter(appDocDir.path);
Hive.registeradapter(NotesModelAdapter());
await Hive.openBox<List<NotesModel>>("Notes");
runApp(MyApp());
}
这是适配器文件
class NotesModelAdapter extends TypeAdapter<NotesModel> {
@override
final int typeId = 1;
@override
TimeBlockModel read(BinaryReader reader) {
final numOfFields = reader.readByte();
final fields = <int,dynamic>{
for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),};
return NotesModel(
title: fields[0] as String,description: fields[1] as String,);
}
@override
void write(BinaryWriter writer,NotesModel obj) {
writer
..writeByte(4)
..writeByte(0)
..write(obj.title)
..writeByte(1)
..write(obj.description);
}
@override
int get hashCode => typeId.hashCode;
@override
bool operator ==(Object other) =>
identical(this,other) ||
other is TimeBlockModelAdapter &&
runtimeType == other.runtimeType &&
typeId == other.typeId;
}
这是我遇到的错误。
Unhandled Exception: HiveError: Cannot write,unkNown type: String. Did you forget to register an adapter?
注意:这是我第二次在同一个应用程序中使用 hive。第一个蜂巢箱工作正常,但当时我没有保存 List。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。