【问题标题】:How do I use a StreamProvider from a StateNotifierProvider?如何使用 StateNotifierProvider 中的 StreamProvider?
【发布时间】:2021-05-21 16:18:08
【问题描述】:

我正在尝试使用来自 StateNotifierProvider 的 StreamProvider。

这是我的 StreamProvider,目前运行良好。

final productListStreamProvider = StreamProvider.autoDispose<List<ProductModel>>((ref) {
  CollectionReference ref = FirebaseFirestore.instance.collection('products');
  return ref.snapshots().map((snapshot) {
    final list = snapshot.docs
        .map((document) => ProductModel.fromSnapshot(document))
        .toList();
    return list;
  });
});

现在我正在尝试填充我的购物车,以便从头开始包含所有产品。

final cartRiverpodProvider = StateNotifierProvider((ref) => 
new CartRiverpod(ref.watch(productListStreamProvider));

这是我的 CartRiverPod 状态通知器

class CartRiverpod extends StateNotifier<List<CartItemModel>> {

  CartRiverpod([List<CartItemModel> products]) : super(products ?? []);

  void add(ProductModel product) {
    state = [...state, new CartItemModel(product:product)];
    print ("added");
  }

  void remove(String id) {
    state = state.where((product) => product.id != id).toList();
  }
}

【问题讨论】:

    标签: flutter dart state provider riverpod


    【解决方案1】:

    完成此操作的最简单方法是接受 Reader 作为 StateNotifier 的参数。

    例如:

    class CartRiverpod extends StateNotifier<List<CartItemModel>> {
      CartRiverpod(this._read, [List<CartItemModel> products]) : super(products ?? []) {
        // use _read anywhere in your StateNotifier to access any providers.
        // e.g. _read(productListStreamProvider);
      }
    
      final Reader _read;
    
      void add(ProductModel product) {
        state = [...state, new CartItemModel(product: product)];
        print("added");
      }
    
      void remove(String id) {
        state = state.where((product) => product.id != id).toList();
      }
    }
    
    final cartRiverpodProvider = StateNotifierProvider<CartRiverpod>((ref) => CartRiverpod(ref.read, []));
    
    

    【讨论】:

    • 亚历克斯,非常感谢!这正是我想要的。
    • @RahulDenmoto 不客气。请将答案标记为已接受,以帮助未来的读者。很高兴它对你有用!
    猜你喜欢
    • 2020-08-14
    • 2021-03-19
    • 2021-09-23
    • 2021-02-03
    • 2021-12-28
    • 1970-01-01
    • 2020-07-24
    • 2020-08-08
    • 1970-01-01
    相关资源
    最近更新 更多