如何使用 StateNotifierProvider 中的 StreamProvider?

问题描述

我尝试使用 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 StateNotifier

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();
  }
}

解决方法

完成此操作的最简单方法是接受 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,[]));