首页 > 解决方案 > Flutter HiveDB 从数据库中删除

问题描述

在我们的文档中,Hive我们有delete从数据库中删除某些内容的方法,但是这种方法不会从数据库中删除,它只null对找到的数据进行索引,当我们想要监听数据库更改或ListView使用null数据时,它会导致一些问题,

另一个问题是.values返回non-nullable数据,当我们尝试做一个ListView我们得到null错误

late Box<Sal> _sal;
useEffect((){
  _sal = Hive.box<Sal>('sal') ;
});

// ...
ValueListenableBuilder(
  valueListenable: _sal.listenable(),
  builder: (_, Box<Sal> sal, __) => ListView.builder(
    physics: const NeverScrollableScrollPhysics(),
    shrinkWrap: true,
    padding: EdgeInsets.zero,
    itemBuilder: (context, index) {
      return Container(
        height: 50.0,
        margin: EdgeInsets.symmetric(vertical: 0.0),
        child: Card(
          color: DefaultColors.$lightBrown,
          child: Row(
            children: [
              CText(
                text: _sal.get(index)!.salName,
                color: Colors.white,
                style: AppTheme.of(context).thinCaption(),
              ).pOnly(right: 16.0),
              const Spacer(),
              IconButton(
                icon: Icon(
                  Icons.edit,
                  color: Colors.yellow,
                ),
                onPressed: () => showGeneralDialog(
                  //...
                ),
              ),
              IconButton(
                icon: Icon(
                  Icons.delete,
                  color: Colors.white,
                ),
                onPressed: () => showGeneralDialog(
                  //...
                ),
              ),
            ],
          ),
        ),
      );
    },
    itemCount: _sal.values.length,
  ),
).pSymmetric(
  h: 16,
),

//...
}

标签: flutterdarthivedb

解决方案


我找到了解决这个问题的方法

late Box<Sal> _sal;
late List<Sal> _data;
useEffect(() {
  _sal = Hive.box<Sal>('sal');
  _data = _sal.values.toList();
});

//...

ValueListenableBuilder(
  valueListenable: Hive.box<Sal>('sal').listenable(),
  builder: (_, Box<Sal> sal, __) {
    _data = _sal.values.toList();
    return ListView.builder(
    physics: const NeverScrollableScrollPhysics(),
    shrinkWrap: true,
    padding: EdgeInsets.zero,
    itemBuilder: (context, index) {
      return Container(
        height: 50.0,
        margin: EdgeInsets.symmetric(vertical: 0.0),
      );
    },
    itemCount: _data.length,
  );
  },
),
//...

推荐阅读