【发布时间】:2021-08-25 06:03:51
【问题描述】:
我想创建一个页面,将所选项目放在最喜欢的页面上,所以我找到了 Hive 数据库,并在它的文档中找到了如何正确执行此操作。我尝试过这种方式,但现在我被卡住了,因为没有选择最喜欢的项目并将其放在另一个页面上。我也在尝试另一种方法:我创建了函数 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),
onPressed: () {
if (box.containsKey(food[index].ttId)) {
box.delete(food[index].ttId);
} else {box.put(food[index].ttId, food);}
}));
});
2d 页面:
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.clear,
color: Colors.red,
),
onPressed: () {
favoriteFoodBox.delete(food[index].ttId);
},
),
);
【问题讨论】:
标签: flutter dart flutter-hive