Flutter Hive Box 删除功能不起作用

问题描述 投票:0回答:1

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");
    }
  }
}

我向 Hive Box 添加项目没有问题,但无法删除它们,没有错误,我尝试通过 Id 删除它们,但它们就是不会删除

flutter hive box cubit
1个回答
0
投票

使用 add 添加到 hive 框中的值是随机键,您应该使用

put
添加数据以换取 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');
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.