BlocListener只返回初始加载状态
创始人
2024-12-22 21:30:24
0

要确保 BlocBuilder 或 BlocProvider 的状态是在 BlocListener 中更新的,否则 BlocListener 将始终接收到初始加载状态。解决方法是在需要更新状态的 BlocBuilder 或 BlocProvider 中使用一个新变量来存储当前状态,并在需要更新状态时使用一个新的方法来更新该变量。

例如,假设我们有一个 CounterBloc,它会根据用户操作更新状态。我们可以使用以下代码来解决该问题:

class CounterBloc extends Bloc {
  CounterBloc() : super(0);

  @override
  Stream mapEventToState(CounterEvent event) async* {
    if (event == CounterEvent.increment) {
      yield state + 1;
    } else if (event == CounterEvent.decrement) {
      yield state - 1;
    }
  }
}

class CounterWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => CounterBloc(),
      child: BlocBuilder(
        builder: (context, state) {
          return Text('$state');
        },
      ),
    );
  }
}

class CounterPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Counter'),
      ),
      body: BlocListener(
        listener: (context, state) {
          print('Counter state changed to $state');
        },
        child: CounterWidget(),
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          FloatingActionButton(
            onPressed: () =>
                context.read().add(CounterEvent.increment),
            child: Icon(Icons.add),
          ),
          SizedBox(height: 8),
          FloatingActionButton(
            onPressed: () =>
                context.read().add(CounterEvent.decrement),
            child: Icon(Icons.remove),
          ),
        ],
      ),
    );
  }
}

在这个例子中,我们使用 BlocProviderBlocBuilder 来创建并显示计数器的当前值。在 CounterPage 中使用 BlocListener 来监听计数器的状态变化。

要确保 BlocListener 正确更新状态,我们必须在 CounterBloc 中使用 yield 来更新状态,并在 BlocBuilder 中使用一个新的变量来存储当前值。然后在 BlocListener 中监听该变量的变化,而不是 CounterBloc 直接返回的值。

使用这种方法,我们

相关内容

热门资讯

透视脚本!wepoker底牌透... wepoker底牌透视脚本app新手教程相关信息汇总(需添加指定Q群1067239143获取下载链接...
透视软件!wepoker透视底... 透视软件!wepoker透视底牌脚本,wpk透视怎么安装,我来教教你(本来有挂);(需添加指定Q群1...
透视真的!德普之星有没有挂,w... 透视真的!德普之星有没有挂,wpk辅助器,透明挂教程(本来是有挂);一、德普之星有没有挂AI软件牌型...
辅助透视!智星德州菠萝安装,w... 辅助透视!智星德州菠萝安装,wepoker可以透视码,存在挂教程(从来存在有挂);揭秘教程安装方法样...
透视透视!德普之星辅助正版,w... 透视透视!德普之星辅助正版,werplan怎么透视,揭秘攻略(本然存在有挂);德普之星辅助正版软件透...
透视线上!hhpoker透视脚... 透视线上!hhpoker透视脚本下载,德普之星透视辅助插件,力荐教程(原本是有挂)1、不需要AI权限...
透视有挂!wepoker免费永... 透视有挂!wepoker免费永久脚本,wpk透视辅助方法,攻略教程(往昔是有挂);wepoker免费...
透视ai!智星菠萝辅助器,hh... 透视ai!智星菠萝辅助器,hhpoker德州挂真的有吗,辅助教程(原先是有挂);科技详细教程Q群《1...
透视安装!红龙poker辅助,... 这是一款非常优秀的红龙poker辅助 ia辅助检测软件,能够让你了解到红龙poker辅助中牌率当中全...
透视好友!wepoker免费透... 透视好友!wepoker免费透视脚本,德州辅助工具到底怎么样,新2025版(果然真的是有挂);玩家在...