首页 > 解决方案 > 卡在肘上,将状态更改为 2 个小部件

问题描述

我的基本代码为 cubit 工作,以更新我的应用程序列表视图中连续的类中的简单计数器。

我想使用bottomNavigationBar 和totalbagel 字段更新总项目的计数器,该字段与我的cubit 在不同的类中。我将导航栏文本字段 totalbabgel 包裹在一个块中,见下文。

我的问题是我不知道如何调用底部导航栏变量中的 cubit 字段。

从我的 cubit 类中引用状态变量的正确格式是什么?所有在线示例仅显示同一类文本更新中的肘状态。我需要在 2 个小部件中更新状态。

文本

     bottomNavigationBar: BottomAppBar(
            child: Row(
              children: [
                //IconButton(icon: Icon(Icons.menu), onPressed: () {}),
                Spacer(),
                Container(
                  height: 55.0,
                  width: 1.0,
                ),
                //TODO get bakerdoz and etotal on footer working need to pass data between main and bagelcounter
    
              BlocBuilder<CounterCubit, CounterCubitState>(
                        key: UniqueKey(),
                        builder: (context,state)
                         => Text("Baker's Dozen: " +  $totalbagels  + "    Singles:  $singles",
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 20.0,
                        fontWeight: FontWeight.w500)),
    
              ),


my test cubit  increment code:

 

       CounterCubit()
          : super(CounterCubitInitial(dozcount: 0, singcount: 0, totalbagels: 0));
    
      void increment() {
        int  holdcart = (state.totalbagels + 1);
        holdtotal = ((state.totalbagels + 1) ~/ 13);
        holdsingle = ((state.totalbagels + 1) % 13);
        print("+holdsingle: " + holdsingle.toStringAsFixed(2));
        print("+holdtotal: " + holdtotal.toStringAsFixed(2));
        print("+holdcart: " + holdcart.toStringAsFixed(2));
        CartTotal(holdcart);
    
        emit(CounterCubitIncreased(
          totalbagels: (state.totalbagels + 1),
          // dozcount: ((state.totalbagels +1) ~/ 13),
          singcount: ((state.totalbagels +1) % 13),
    
          // singcount: ((state.totalbagels +1) % 13),
        ));
      }

标签: fluttercubit

解决方案


您可以处理状态。如果您为 cubit 定义了状态,则可以在 BlocBuilder 中使用状态

  key: UniqueKey(),
  builder: (context,state) {
    if(state is CounterCubitInitial) {
        return Text();
    } else if (state is CounterCubitIncreased) {
        return Text("Baker's Dozen: " +  state.totalbagels  + "    Singles:  ${state.singles}",
                  style: TextStyle(
                  color: Colors.white,
                  fontSize: 20.0,
                  fontWeight: FontWeight.w500));
    }
  }           
);

推荐阅读