简体   繁体   English

块 state 未更新

[英]Bloc state not updating

I'm a bit confused as to why the cart counter is not updating when I select multiple items.当我 select 多个项目时,为什么购物车计数器没有更新,我有点困惑。 It just shows 0. I have to switch between tabs to get the counter to change to the correct value.它只显示 0。我必须在选项卡之间切换才能让计数器更改为正确的值。

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
        ),
    )
  )
),

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.不确定,因为我从未设置过这样的集团——但据我所知,你的代码并没有改变 state。 You always only use _cartController.sink.add(cart);你总是只使用_cartController.sink.add(cart); . . However, in order to update the ui, the state needs to change.但是,为了更新 ui,state 需要更改。 So I always start on an event reaction with an InProgressState before I update the data with an DisplayDataState .因此,在使用DisplayDataState更新数据之前,我总是从InProgressState的事件反应开始。

Anyways, maybe it is easier to use the bloc and the bloc_provider package and work with mapEventToState无论如何,使用 bloc 和 bloc_provider package 并使用mapEventToState可能更容易

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM