Home > Software design >  Using Hive deleteAt() crashes my flutter project due to a NULL error
Using Hive deleteAt() crashes my flutter project due to a NULL error

Time:04-03

I have a list of objects called Weeks in my project and after I run the delete function to remove items from my Hive box the code runs fine. But then when I restart the app and it initializes and loads items from the box I get this error:

_TypeError (type 'Null' is not a subtype of type 'Week')

My delete function looks like this:

  //Delete Week
  void deleteWeek({required int weekIndex}) {
    print(box.length);
    listOfWeeks.removeAt(weekIndex);
    box.deleteAt(weekIndex);
    print(box.length);

    notifyListeners();
  }

I thought at first maybe I was deleting too much from box, so I print out the length and the length goes down by one after it runs box.deleteAt(weekIndex); in the above function.

My add week function works perfect and has no issues after restarting the app:

  void addWeek({
    required double budget,
  }) {
    Week newWeek = Week(
      budget: budget,
    );

    listOfWeeks.add(newWeek);
    box.add(newWeek);
    notifyListeners();
  }

Since the delete function is basically the add function in reverse I am not sure what I am doing wrong. My only hypothesis at this point is that the box.deleteAt() function is not operating how I expect it too. Does it not work similar to the listOfWeeks.removeAt(weekIndex); ?

For more info, the weeks class initializes with this at restart:

@HiveType(typeId: 1)
class WeekList extends ChangeNotifier {
  WeekList() {
    print("Loading box");
    int boxLength = box.length;
    for (var i = 0; i < boxLength; i  ) {
      listOfWeeks.add(box.get(i));
    }
  }

CodePudding user response:

This is because of null safety. When the project first initialises, the value is first Null, which is not null-safe.

To make a function return type as able to hold null then you need to mark it with a ?, e.g.:

Week? getWeek(){….}

More info is here: https://dart.dev/null-safety

CodePudding user response:

The question doesn't have clarity. If you can edit the question and add the full code. You are doing some things wrongly.

  1. When deleting an object from Hive box , the best practice is to pass the key instead of the index. You can simply access the key by just calling objectName.key. and for deleting use boxName.delete(objectName.key).

  2. When you deleting , you only need to delete from Hive box.No need to remove from the list. Make the list listen to the changes of hive box. It is the proper way to do it.

I can provide you the answer if you share some more information

  • Related