问题描述
我正在从我创建的 MyClass 文件中预定义的列表构建我的小部件。这行得通,但我希望能够存储持久化数据以添加布尔收藏夹字段。
我为我的类创建了 Hive 类型/字段,生成了类型适配器,并在应用程序第一次运行时成功加载了 Hive 框,我可以将值打印到控制台,所以我知道数据就在那里正确。
在我拥有的课程中,名称、图像 url 资产图像的路径和收藏夹字段。
Expanded(child: Image.asset(widget.MyClass.imageURL)),
现在我想从 Hive 框中获取这个
Box<MyClass> Box = Hive.Box<MyClass>('myClassBox');
//This is where I am stuck
Expanded(child: Image.asset(Box.???)),
我尝试了 Box.values.where 和 Box.get() 然后进入 imageURL 字段。但是 get 需要一个密钥,我不必从
Widget build(BuildContext context)
然后我在尝试访问收藏夹字段时遇到了同样的问题,我使用的是收藏夹按钮包 (favorite_button 0.0.4)。然后我将根据被点击的按钮更新真/假值。
如果有人能指出我正确的方向,那就太好了。
谢谢。
编辑:
这是小部件:
Widget build(BuildContext context) => GestureDetector(
onTap: () => Navigator.of(context).push(MaterialPageRoute(
builder: (context) => TaskPage(job: widget.job),//Need to get data from Hive Now
)),child: Container(
padding: const EdgeInsets.all(16),height: 100,decoration: Boxdecoration(
borderRadius: BorderRadius.circular(16),),child: Row(
children: [
Expanded(flex: 3,child: buildText()),Expanded(child: Image.asset(widget.job.imageUrl)),//Need to get data from Hive Now
GestureDetector(
child: Icon(
widget.job.fav ? Icons.favorite : Icons.favorite_border,//Need to get data from Hive Now
),onTap: () {
// add/remove from favorites list
}
),],);
第二次编辑:这是执行给定建议后的相同代码
Widget build(BuildContext context) => GestureDetector(
onTap: () => Navigator.of(context).push(MaterialPageRoute(
builder: (context) => TaskPage(job: Hive.Box<Job>('jobBox').get(context)),//This bit is still broken so I need to look at this
)),child: Column(
children:
Hive.Box<Job>('jobBox').values.toList().map(
(elementList) => Container(
padding: const EdgeInsets.all(16),decoration: Boxdecoration(
color: white,borderRadius: BorderRadius.circular(16),child: Row(
children: [
Expanded(flex: 3,child: Column(
crossAxisAlignment: CrossAxisAlignment.start,mainAxisAlignment: MainAxisAlignment.center,children: [
Text(
elementList.name,style: TextStyle(fontWeight: FontWeight.w500,fontSize: 20),SizedBox(height: 10),//Text('Num tasks in job'),)),Expanded(child: Image.asset(elementList.imageURL)),GestureDetector(
child: Icon(
elementList.fav
? Icons.favorite
: Icons.favorite_border,color: elementList.fav ? Colors.red.shade200 : Colors.grey,onTap: () {
//To do
}
// )
),)
.toList(),);
解决方法
假设框中只有 1 个数据,您可以像这样访问存储的数据。
Box<MyClass> box = Hive.box<MyClass>('myClassBox');
if(box.isNotEmpty) {
final data = box.values.first;
// use data
} else {
// empty state
}
Hive 值可以有键,这取决于您如何使用它。如果您使用了 box.put(key,value)
,则可以使用 box.get(key)
来处理键和值。
如果您使用 box.add(value)
,它会存储从 0 开始自动分配索引的数据。因此您可以使用 box.getAt(index)
获取带索引的数据。