我正在尝试使用bloc模式构建购物车,这是我第一个扑扑的应用程序,也是使用bloc。我的问题是,每次用户将产品添加到购物车时,我都试图获取int流。但似乎我在使用接收器和流时出错,但我不知道确切的位置
ItemCounterBloc
final _itemCounterSubject = BehaviorSubject<int>(seedValue: 0);
final _cartItemsController = StreamController<List<CartItem>>();
int count = 0;
ItemCounterBloc(Item item){
_cartItemsController.stream
.map((list) => list.any((cartItem)=> cartItem.item == item))
.listen((increment){
count += 1;
_itemCounterSubject.add(count);
});
}
Sink<List<CartItem>> get cartItems => _cartItemsController.sink;
ValueObservable<int> get isInCart => _itemCounterSubject.stream.distinct().shareValue(seedValue: 0);
void dispose(){
_cartItemsController.close();
_itemCounterSubject.close();
}
}
计数器
StreamBuilder<int>(
stream: _bloc.isInCart,
initialData:0,
builder: (context, snapshot) => Text('${snapshot.data}')
我还有另一个将商品添加到购物车的集团。
答案 0 :(得分:0)
有一个有关如何构建购物车系统的完整示例。 包括以下部分:
https://github.com/Ephenodrom/FlutterAdvancedExamples/tree/master/lib/examples/shoppingCart
这就是您的BLOC的外观:
class ShoppingCartBloc implements BlocBase {
static const String TAG = "ShoppingCartBloc";
ShoppingCart cart = ShoppingCart();
/// Sinks
Sink<Product> get addition => itemAdditionController.sink;
final itemAdditionController = StreamController<Product>();
Sink<Product> get substraction => itemSubtractionController.sink;
final itemSubtractionController = StreamController<Product>();
/// Streams
Stream<ShoppingCart> get cartStream => _cart.stream;
final _cart = BehaviorSubject<ShoppingCart>();
ShoppingCartBloc() {
itemAdditionController.stream.listen(handleItemAdd);
itemSubtractionController.stream.listen(handleItemRem);
}
///
/// Logic for product added to shopping cart.
///
void handleItemAdd(Product item) {
Logger(TAG).info("Add product to the shopping cart");
cart.addProduct(item);
cart.calculate();
_cart.add(cart);
return;
}
///
/// Logic for product removed from shopping cart.
///
void handleItemRem(Product item) {
Logger(TAG).info("Remove product from the shopping cart");
cart.remProduct(item);
cart.calculate();
_cart.add(cart);
return;
}
///
/// Clears the shopping cart
///
void clearCart() {
cart.clear();
}
@override
void dispose() {
itemAdditionController.close();
itemSubtractionController.close();
}
}
class ShoppingCart {
List<Product> products = [];
double priceNet;
double priceGross;
double vatAmount;
void addProduct(Product p) {
products.add(p);
}
void remProduct(Product p) {
products.remove(p);
}
void calculate() {
priceNet = 0;
priceGross = 0;
vatAmount = 0;
products.forEach((p) {
priceNet += p.priceNet;
priceGross += p.priceGross;
vatAmount += p.vatAmount;
});
}
void clear() {
products = [];
priceNet = 0;
priceGross = 0;
vatAmount = 0;
}
}
class Product {
final String name;
final double priceNet;
final double priceGross;
final double vatAmount;
final double tax;
Product(
{this.name, this.priceNet, this.priceGross, this.vatAmount, this.tax});
}