【问题标题】:Bloc state not updating集团状态未更新
【发布时间】:2021-03-17 10:05:42
【问题描述】:

我有点困惑,为什么当我选择多个商品时购物车计数器没有更新。它只显示 0。我必须在选项卡之间切换才能让计数器更改为正确的值。

购物车

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

主屏幕

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

【问题讨论】:

    标签: flutter dart bloc


    【解决方案1】:

    不确定,因为我从未设置过这样的集团 - 但据我所知,您的代码并没有改变状态。你总是只使用_cartController.sink.add(cart);。但是,为了更新 ui,需要更改状态。因此,在使用 DisplayDataState 更新数据之前,我总是从 InProgressState 开始事件反应。

    无论如何,使用 bloc 和 bloc_provider 包并使用 mapEventToState 可能更容易

    【讨论】:

      猜你喜欢
      • 2015-06-11
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-07
      • 2022-01-05
      相关资源
      最近更新 更多