0

In my Flutter App I have a Hive box with Player objects. Just to debug I'm outputting some data from my player objects in the constructor, like this:

  Player({
    @required String name,
    @required this.id,
  }) {
    this.name = name.toUpperCase();
    print('${this.toString()}');
  }

  @override
  String toString() {
    return 'id: $id, name: $name';
  }  

The players are added to the box like this, where player.id is a unique key:

  playerBox.put(player.id, player);

When starting the app I also print the values of the playerBox:

 print (playerBox.values);

Which gives me all the added players. So far so good. But... After deleting a player like this:

 playerBox.delete(playerId);

It starts behaving a bit weird. When I restart the app, the deleted player is no longer in playerBox.values, so it's obviously deleted from there. But the constructors from all the deleted player objects are still run.

Checking the stack I can see that these objects are indeed instantiated by the PlayerAdapter. So for some reason the deleted objects are still read from disk by Hive, but they're not in the box.

** EDIT

I also checked the player.hive file on my emulator, and all the deleted models are actually in the file. Even though they're deleted and won't be returned with playerBox.values

Any ideas what the reason might be? Is this expected behaviour?

Christoffer
  • 7,470
  • 9
  • 39
  • 55

1 Answers1

4

Answering this myself.

Any ideas what the reason might be? Is this expected behaviour?

Yes and yes. I guess I should have checked these docs more careful: Compaction

Hive is an append-only data store. When you change or delete a value, the change is written to the end of the box file. Sooner or later, the box file uses more disk space than it should. Hive may automatically "compact" your box at any time to close the "holes" in the file.

So I solved this by compacting the box after deleting like this:

playerBox.compact();
Christoffer
  • 7,470
  • 9
  • 39
  • 55