i get error _TypeError (type ‘List<dynamic>’ is not a subtype of type ‘List<MessageModel>’ in type cast) but if i delete the hive from the disk it work
here i init Hive
Future initHive() async {
await Hive.initFlutter();
if (!Hive.isAdapterRegistered(MessageEnumAdapter().typeId)) {
Hive.registerAdapter(MessageEnumAdapter());
}
if (!Hive.isAdapterRegistered(UserModelAdapter().typeId)) {
Hive.registerAdapter(UserModelAdapter());
}
if (!Hive.isAdapterRegistered(MessageModelAdapter().typeId)) {
Hive.registerAdapter(MessageModelAdapter());
}
if (!Hive.isAdapterRegistered(ChatModelAdapter().typeId)) {
// only register if MessageModelAdapter is already registered
if (Hive.isAdapterRegistered(MessageModelAdapter().typeId)) {
Hive.registerAdapter(ChatModelAdapter());
}
}
// if the box is not exist, create new box
if (!Hive.isBoxOpen(hiveChatBox)) {
hive = await Hive.openBox<ChatModel>(hiveChatBox);
}
// return hive;
}
and this is chatModelAdapter
class ChatModelAdapter extends TypeAdapter<ChatModel> {
@override
final int typeId = 0;
@override
ChatModel read(BinaryReader reader) {
return ChatModel(
id: reader.read() as String,
chatType: reader.read() as String,
participants: reader.read() as List<String>,
createdAt: reader.read() as DateTime,
numberOfNewMessages: reader.read() as int,
lastMessage: reader.read() as MessageModel?,
messages: reader.read() as List<MessageModel>,
);
}
@override
void write(BinaryWriter writer, ChatModel obj) {
writer.write(obj.id);
writer.write(obj.chatType);
writer.write(obj.participants);
writer.write(obj.createdAt);
writer.write(obj.numberOfNewMessages);
writer.write(obj.lastMessage);
writer.write(obj.messages);
}
}
the chatModel is combined with more then one model MessageModel. i have anther Hive box of user model that more simple and it work there.
2
Answers
I guess this doesn’t work:
You need to cast every element to a type of MessageModel and add it to your new List of type MessageModel.
You can do it like this:
The read() method is returning a
List<dynamic>
, but you are trying to cast it directly toList<MessageModel>
.You can try:
This might solve the issue.
Link – https://api.flutter.dev/flutter/dart-core/Iterable/map.html