0

Sample

  deleteItem(int index) {
    final box = Hive.box<Delivery>("deliveries");

    box.deleteAt(index);
  }

I'd like to change index parameter to the id of my object), like this

  deleteItem(int id) {
    final box = Hive.box<Delivery>("deliveries");

    // box.deleteAt(index);
    // box delete by id here
  }

Here my TypeAdapter class:

@HiveType(typeId: 0)
class Delivery {
  @HiveField(0)
  final int id;

  Delivery(this.id);

}
rmontemayor0101
  • 137
  • 2
  • 8
  • But I think your value can be duplicated, and you can do it by using an iterator and if statement like: `value == "Hello"` then delete the value from your list. – Abbas Jafari Mar 02 '21 at 12:28

2 Answers2

4

As stated in the other answer, this is not possible unless you search for every item and compare their ID's one by one. Depending on the number of itens in your box, this may take longer or may not matter at all.

One example of this unoptimized way would be:

  deleteItem(int id) {
    final box = Hive.box<Delivery>("deliveries");

    final Map<dynamic, Delivery> deliveriesMap = box.toMap();
    dynamic desiredKey;
    deliveriesMap.forEach((key, value){
        if (value.id == id)
            desiredKey = key;
    });
    box.delete(desiredKey);
  }

What this code does is to turn the Box class into a Map, using the toMap() method. With a map in hands, we iterate through every entry on it, checking which one has the specific ID and keep record of that. After that we just delete the found key using the delete() method. You can read more about iterating through Maps here..

Keep in mind that this is only an example. If you try to use this you probably will need to check if there is really an item with the ID you are searching for. If it's the case, you also need to check for multiple values with the same ID in your Box.

Naslausky
  • 3,443
  • 1
  • 14
  • 24
1

Think of a key-value database as a regular good old vocabulary with words and their definitions. It allows you to find a definition using given word very quickly (let's say you are looking for the word elephant). However, if you wanted to find an entry with definition that says An animal with big ears., it would take you much longer time.

With a lot of simplification, that's how the key-value databases work. They are fast when you query using the index.

So if you want to query using the id, I would recommend using the id in the index itself.

For example:

Indexes:

delivery-001
delivery-002
...

Or, if you also want to perform some other more complicated queries, I would recommend using a regular SQLite database using sqflite.