2
 void deleteTask(int index) {
    setState(() {
      db.toDoList.removeAt(index);
    });
    db.updateDataBase();
  }

This is what the delete function looks like. How can I make the edit function for hive using flutter in that manner as above stated?

padaleiana
  • 955
  • 1
  • 14
  • 23
Amila
  • 63
  • 7

1 Answers1

3

Using the Hive database, there is a get(), getAt() put(), putAt(), delete(), deleteAt() methods that are well-documented from it's official documentation.

Hive is a key-value based database, there is no update() method by default, but you can achieve the same as only with the provided methods (getAt() and putAt()).

Considering that I have a "stringText" value stored on the 5 index, as we know to get it from a box, we can do the:

String valueFromTheBox = box.getAt(5); // "stringText"

And, in order to achieve and update this value, we simply need to assign a new value to that valueFromTheBox variable and put it again on the same key using putAt() like this:

valueFromTheBox = "newValueTHatWillBePut";
box.putAt(5);

This will literally make an update method, so in order to make a full function that achieves, and based on your case we can do:

void updateTask(int index) {
 SetState(() {
  
  dynamic task = db.toDoList.getAt(index); // get previous task
  task = changeSomethingAndReturn(previousTask); // change/edit the task
  db.toDoList.putAt(index, task); // assign the task on same index 
 
  });
  
  db.updateDataBase();

}

And you need to replace changeSomethingAndReturn() method with your method that takes the task and makes changes over it then returns the new changed one.

Note: I don't recommend letting the dynamic type, since it's not mentioned in your question, I'm using it, but you should specify its type so you prevent getting into errors.

Gwhyyy
  • 7,554
  • 3
  • 8
  • 35
  • thank you @Gwhyy and do i have to add the prviousTask thing its kind of a hassle – Amila Nov 27 '22 at 05:00
  • using Hive, you have no other option to update an element than getting it, then make changes on it, then put it again on the same index. – Gwhyyy Nov 27 '22 at 05:02
  • may I asking you why you need to use setState on this ? – Gwhyyy Nov 27 '22 at 05:03
  • 1
    No reason if there is a other way please tell (I'm a 14 year old beginner) – Amila Nov 27 '22 at 05:04
  • The Hive package can be combined with the ValueListenableWidget which could listen automatically to box changes, so whenever any change like using `deleteAt`, `putAt()` and this `update()` methods, automatically it will update state based on it without needing to use setState(() {}) every time. – Gwhyyy Nov 27 '22 at 05:07
  • check it from here https://docs.hivedb.dev/#/basics/hive_in_flutter?id=valuelistenable – Gwhyyy Nov 27 '22 at 05:08