问题描述
我想在 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 (将#修改为@)