我如何使用一个StreamProvider从StateNotifierProvider?



我正在尝试使用来自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 statenotify

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, []));

最新更新