【问题标题】:Shopping cart using bloc does not update cart count使用 bloc 的购物车不会更新购物车数量
【发布时间】:2021-03-17 21:05:49
【问题描述】:

我正在尝试使用 bloc 构建一个简单的购物车。它工作正常,但唯一的问题是当我添加/删除项目时购物车计数没有得到更新。我需要切换到购物车屏幕才能看到更改。我将计数器设置为 cartBloc.cart.length.toString()。我错过了什么,我是否正确使用 bloc?

购物车组

class CartBloc{

  List<ProductModel> cart = [];
  double totalCartPrice = 0;

  final _cartController = StreamController.broadcast();
  Stream get getCartStream => _cartController.stream;

  void addToCart(ProductModel product) {
    cart.add(product);
    totalCartPrice = totalCartPrice + double.parse(product.price);
    _cartController.sink.add(cart);
  }
  void removeFromCart(ProductModel product) {
    cart.remove(product);
    totalCartPrice = totalCartPrice - double.parse(product.price);
    _cartController.sink.add(cart);
  }
  void dispose() {
    _cartController?.close();
  }
}
final cartBloc = CartBloc();

主屏幕

class _MainScreenState extends State<MainScreen> {

      int _currentIndex = 0;
      PageController _pageController;
      GlobalKey bottomNavigationKey = GlobalKey();

      @override

      void initState() {
        super.initState();
        _pageController = PageController();
      }
      
      void dispose(){
        super.dispose();
        _pageController.dispose();
      }

      @override

      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor:Color(0xFF20232A),
          appBar: PreferredSize(child: Container(),preferredSize: Size.fromHeight(0.0)),
          body: SizedBox.expand(
            child: PageView(
              physics: NeverScrollableScrollPhysics(),
              controller: _pageController,
              onPageChanged: (index){
                setState(() => _currentIndex = index);
              },
              children: [
                Container(
                  child: ProductScreen()
                ),
                Container(
                  child: CartScreen()
                ),
              ],
            )
          ),
          bottomNavigationBar: Container(
            child: BottomNavyBar(
              mainAxisAlignment: MainAxisAlignment.center,
              containerHeight: 56.0,
              backgroundColor: Style.Colors.backgroundColor,
              selectedIndex: _currentIndex,
              onItemSelected: (index){
                setState(() => _currentIndex = index);
                _pageController.jumpToPage(index);
              },
              items:<BottomNavyBarItem>[
                BottomNavyBarItem(
                  textAlign: TextAlign.center,
                  activeColor: Color(0xFF010101),
                  title: Text(' PRODUCTS',style: TextStyle(
                    color:Style.Colors.mainColor,fontSize: 13.0
                  )),
                  icon: Padding(
                    padding: EdgeInsets.only(left:5.0),
                    child: Icon(
                      SimpleLineIcons.menu,
                      size:18.0,
                      color:_currentIndex == 0 ? Style.Colors.mainColor:Colors.white
                    ),
                  )
                ),
                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.cart.length.toString(),style: TextStyle(fontWeight: FontWeight.bold),), //not updating when select item
                        child: Icon(
                          SimpleLineIcons.basket,
                          size:18.0,
                          color:_currentIndex == 1 ? Style.Colors.mainColor:Colors.white
                        ),
                    )
                  )
                ),
              ]
            ),
          ),
        );
      }
    }

【问题讨论】:

    标签: flutter dart bloc


    【解决方案1】:

    您在使用 Bloc 时做错了很多事情。

    例如:

    您的CartBloc 需要像这样扩展 Bloc 类:

    class CartBloc extends Bloc<SomeEvent, SomeState>
    

    那么你需要像这样覆盖那个类中的mapEventToState方法。

    @override
      Stream<SomeState> mapEventToState(SomeEvent event) async* {
    

    那么您需要使用以下方式提供您的 Bloc:

    BlocProvider(
          create: (_) => CartBloc(),
          child: YourWidget()
    )
    

    然后使用 BlocBuilder 使用 CartBloc 中的数据构建您的小部件

    我建议你看一下关于如何使用 bloc 的文档和示例 https://pub.dev/packages/flutter_bloc/example

    【讨论】:

      猜你喜欢
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-14
      • 2019-06-30
      • 2014-08-29
      • 2019-12-25
      • 1970-01-01
      相关资源
      最近更新 更多