Scouser
Scouser

Reputation: 3

Flutter Hive Box delete function doesn't work

class HomeCubit extends Cubit<HomeState> {
  HomeCubit() : super(HomeInitial());
  var savedBox = Boxes.savedBox;

  addSavedProduct(ProductModel product) {
    savedBox.add(product);
    print(savedBox.length);
    emit(HomeSuccess());
  }

  removeSavedProduct(ProductModel product) {
    try {
      if (product.id != null) {
        savedBox.delete(product.id!);
        emit(HomeSuccess());
      } else {
        print("Invalid product id");
      }
    } catch (e) {
      print("Error removing product: $e");
    }
  }
}

I have no problem adding items to the hive box, but no way to delete them. No errors. I tried to delete them by Id, but they just won't delete.

Upvotes: 0

Views: 134

Answers (1)

rasityilmaz
rasityilmaz

Reputation: 1399

The value you add to the hive box with add is a random key, you should use put to add data in return for an ID.

class HomeCubit extends Cubit<HomeState> {
  HomeCubit() : super(HomeInitial());
  var savedBox = Boxes.savedBox;

  addSavedProduct(ProductModel product) {
    if (product.id == null) {
      savedBox.put(product.id!, product);
    }
    print(savedBox.length);
    emit(HomeSuccess());
  }

  removeSavedProduct(ProductModel product) {
    try {
      if (product.id != null) {
        savedBox.delete(product.id!);
        emit(HomeSuccess());
      } else {
        print('Invalid product id');
      }
    } catch (e) {
      print('Error removing product: $e');
    }
  }
}

Upvotes: 0

Related Questions