skip to Main Content

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


  1. I guess this doesn’t work:

    messages: reader.read() as List<MessageModel>,
    

    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:

    messages: List<MessageModel>.from(reader.read()),
    
    Login or Signup to reply.
  2. The read() method is returning a List<dynamic>, but you are trying to cast it directly to List<MessageModel>.

    You can try:

    messages: (reader.read() as List).map((m) => m as MessageModel).toList()
    

    This might solve the issue.
    Link – https://api.flutter.dev/flutter/dart-core/Iterable/map.html

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search