I want to save List of objects in flutter hive. Is there any way to implement it. I create a model class for notes. That has fields as note title and description. I want to save List in hive flutter with DateTime.now() as Key. Is there any way to implement it?

class NotedBox {
  static Box<List<NotesModel>> getNotedBox() {
    return Hive.box<List<NotesModel>>("Notes");
  }
}

this is my box that I'm opening in the 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());
    }

Here is the Adapter File

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;
}

Here is the error I'm encountering.

 Unhandled Exception: HiveError: Cannot write, unknown type: String. Did you forget to register an adapter?

Note: This is the second time I'm using the hive in the same app. The first hive box is working fine but at that time I wasn't saving List.


Solution 1: Blackshadow

maybe you did not register your adapter in the main method.

Hive.registerAdapter(MyObjectAdapter());

hive