【问题标题】:How to listen to custom key changes in hive and how to listen to all data like firestore snapshot?如何监听 hive 中的自定义键更改以及如何监听所有数据,如 firestore 快照?
【发布时间】:2021-11-10 18:00:51
【问题描述】:

我正在使用 hive,我正在尝试按照下面的代码监听自定义存储键的值变化,但我无法获取任何数据?那么我该如何实现呢?

   Stream<BoxEvent> listenToLocalCartItem(String cartItemId) {
   var box = Hive.box('cart');
   box.watch(key: cartItemId).listen((event) {

    CartItemModel cartItem = event.value;
    if (cartItem.numberOfItems > 0) {
      emit(AddToCartState.showCartValue(cartItem.numberOfItems));
    } else {
      emit(AddToCartState.showAddButton());
    }
  });

}

另一方面,我想跟踪框中的所有数据更改,就像下面的代码一样,就像 firestore 快照一样,我也无法获得任何更改

 Stream<Box> listenToLocalCart() {
Hive.openBox('cart').asStream().listen((event) {
    _cartStatusProvider.cartItems = event.values.toList();
  });
 }

【问题讨论】:

    标签: database flutter dart stream flutter-hive


    【解决方案1】:
    import 'package:hive_flutter/hive_flutter.dart';
    
    
    FutureBuilder(
      future: Hive.openBox<CartItems>('cart'),
      builder: (context, snapshot) {
        return ValueListenableBuilder(
          valueListenable: Hive.box<CartItems>('cart').listenable(),
          builder: (context, Box<CartItems> box, _) {
            if (box.values.isEmpty) {
              return Text('data is empty');
            } else {
              return ListView.builder(
                itemCount: box.values.length,
                itemBuilder: (context, index) {
                  var item = box.getAt(index);
                  return ListTile(
                    title: Text(item.name),
                    subtitle: Text(item.count.toString()),
                  );
                },
              );
            }
          },
        );
      },
    ),
    

    【讨论】:

    • listenable() 未定义
    • @OmarAbdelazeem 您需要添加 hive_flutter 包并按照代码 sn-p 导入 hive_flutter 包
    猜你喜欢
    • 2018-06-09
    • 2020-03-17
    • 2021-11-17
    • 1970-01-01
    • 2019-03-26
    • 2019-05-27
    • 1970-01-01
    • 2018-12-14
    相关资源
    最近更新 更多