参数类型 'List<Food>' 不能分配给参数类型 'Food' Hive db

问题描述

我想创建一个页面,将所选项目放在最喜欢的页面上,所以我找到了 Hive db,在它的文档中我找到了如何正确执行此操作。我试过这种方式,现在我被卡住了,因为没有选择喜欢的项目并放在另一个页面上。我也在尝试另一种方式:我创建了函数 onFavoritePress() 并在 onpressed 函数中使用了 if-else 语句,代码如下所示:

 trailing: IconButton(
                         icon: getIcon(index),onpressed: () {
                            if (Box.containsKey(food[index].ttId)) {
                              Box.delete(food[index].ttId);
                            } else {Box.put(food[index].ttId,food);}
                          }));

但它给出了错误The argument type 'List<Food>' can't be assigned to the parameter type 'Food' 然后我将 Box <Food> Box 更改为 Box<dynamic> Box 并且此错误消失了,但它仍然无法正常工作并且没有在收藏页面上放置任何项目。我很困惑我做错了什么。

整个代码是: 主要内容

main() async {
  await Hive.initFlutter();
  await Hive.openBox<Food>(favoritesBox);

第一页:

class _FoodTState extends State<FoodT> {
  Box<Food> favoriteFoodBox;

  @override
  void initState() {
    super.initState();
    favoriteFoodBox = Hive.Box(favoritesBox);
  }

 body: ValueListenableBuilder(
          valueListenable: favoriteFoodBox.listenable(),builder: (context,Box<Food> Box,child) {
            return ListView.builder(
                itemCount: food.length,itemBuilder: (builder,index) {
                  return ListTile(
                      title: Text(food[index].ttTitle),trailing: IconButton(
                         icon: Icon(Icons.favorite),food);}
                          }));
                });

二维页面

body: ValueListenableBuilder(
        valueListenable: favoriteFoodBox.listenable(),child) {
          return ListView.builder(
              itemCount: food.length,index) {
                return ListTile(
                  title: Text(food[index].ttTitle),trailing: IconButton(
                    icon: Icon(
                      Icons.clear,color: Colors.red,),onpressed: () {
                      favoriteFoodBox.delete(food[index].ttId);
                    },);

解决方法

您为单个 Food 项打开 Hive 框,但在 put 方法中,您正在存储整个列表 (List<Food>) - 这在错误消息中提到。调整您的代码并更新您的 put 方法以存储单个 Food 项目:

trailing: IconButton(
  icon: getIcon(index),onPressed: () {
    if (box.containsKey(food[index].ttId)) {
      box.delete(food[index].ttId);
    } else {
      box.put(food[index].ttId,food[index]); // Changed put method
    }
}));

以前,您存储了整个列表,但您只需按 id 存储单个对象:food -> food[index]