#flutter #dart #state #provider #riverpod
#flutter #dart #состояние #поставщик #riverpod
Вопрос:
Я пытаюсь использовать StreamProvider из StateNotifierProvider.
Вот мой 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));
Это мой 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();
}
}
Ответ №1:
Самый простой способ добиться этого — принять a 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, []));
Комментарии:
1. Алекс, большое тебе спасибо! Это именно то, что я искал.
2. @RahulDenmoto Всегда пожалуйста. Пожалуйста, отметьте ответ как принятый, чтобы помочь будущим читателям. Рад, что у вас все получилось!