Home:ALL Converter>Bloc counter for shopping cart

Bloc counter for shopping cart

Ask Time:2019-02-06T22:06:10         Author:Abdulaziz Alhadhoud

Json Formatter

I am trying to build a shopping cart using the bloc pattern as this my first app in flutter as well as using bloc. my problem is that I am trying to get the stream of an int each time the user add the product to the cart. but it seems that I am using the sink and stream wrong but I don't know exactly where

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

Counter

StreamBuilder<int>(
            stream: _bloc.isInCart,
            initialData:0,
            builder: (context, snapshot) => Text('${snapshot.data}')

Also I have another bloc for adding items to the cart.

Author:Abdulaziz Alhadhoud,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/54555511/bloc-counter-for-shopping-cart
yy