How do I get the next free key of my HIVE box, so that I can set it as the ID?

78 Views Asked by At

This is my object.

class Note {
  @HiveField(0)
  final String title;

  @HiveField(1)
  final String content;

  @HiveField(2)
  late String? date;

  @HiveField(3)
  final int? id;

  Note(
      {required this.title,
      required this.content,
      this.date,
      required this.id});
}

And this is my function

 final newNote = Note(
 title: titleController.text,
 content: contentController.text,
 date: DateTime.now().toString(),
 id: 
 );
 noteBox.add(newNote);

The box is auto-incrementing. How do I set the ID of my new note to be the key that it's going to increment to?

I tried setting the id as id: noteBox.length, but that didn't work, because when I deleted one of the notes and created a new one, the IDs would end up being the same sometimes.

UPDATE:

 final newNote = Note(
                  title: titleController.text,
                  content: contentController.text,
                  date: DateTime.now().toString(),
                  id: 0,
                );
                var key = await noteBox.add(newNote);
                final updatedID = Note(
                  title: newNote.title,
                  content: newNote.content,
                  date: newNote.date,
                  id: key,
                );
                noteBox.put(key, updatedID);

This works like I want it to, but it seems unethical. If theres no other way, i'll just stick to this.

0

There are 0 best solutions below