Reputation: 471
I'm a bit confused as to why the cart counter is not updating when I select multiple items. It just shows 0. I have to switch between tabs to get the counter to change to the correct value.
CartBloc
class CartBloc{
List<ProductModel> cart = [];
double totalCartPrice = 0;
int cartCount = 0;
final _cartController = StreamController.broadcast();
Stream get getCartStream => _cartController.stream;
void addToCart(ProductModel product) {
cart.add(product);
cartCount = cartCount + 1;
totalCartPrice = totalCartPrice + double.parse(product.price);
_cartController.sink.add(cart);
}
void removeFromCart(ProductModel product) {
cart.remove(product);
cartCount = cartCount - 1;
totalCartPrice = totalCartPrice - double.parse(product.price);
_cartController.sink.add(cart);
}
void dispose() {
_cartController?.close();
}
}
final cartBloc = CartBloc();
MainScreen
BottomNavyBarItem(
textAlign: TextAlign.center,
activeColor: Color(0xFF010101),
title: Text(' CART',style: TextStyle(
color:Style.Colors.mainColor,fontSize: 13.0
)),
icon: Padding(
padding: EdgeInsets.only(left:5.0),
child: Badge(
badgeColor: Style.Colors.mainColor,
badgeContent: Text(cartBloc.cartCount.toString(),style: TextStyle(fontWeight: FontWeight.bold),),
child: Icon(
SimpleLineIcons.basket,
size:18.0,
color:_currentIndex == 1 ? Style.Colors.mainColor:Colors.white
),
)
)
),
Upvotes: 0
Views: 35
Reputation: 2698
Not sure, since I have never set-up a bloc like this - but as far as I can understand your code you are not changing the state. You always only use _cartController.sink.add(cart);
. However, in order to update the ui, the state needs to change. So I always start on an event reaction with an InProgressState
before I update the data with an DisplayDataState
.
Anyways, maybe it is easier to use the bloc and the bloc_provider package and work with mapEventToState
Upvotes: 0