Bloc 如何监听流并发出状态

How can Bloc listen to stream and emit state

在我的 flutter 应用中,我使用 flutter_bloc 进行状态管理。

有问题的 bloc 使用 repositoryrepository 订阅了一个 websocket,新数据被添加到一个流中。

问题: 我的bloc听流:

InvestmentClubBloc({
    required this.investmentClubRepository
  }) : super(InvestmentClubLoading()) {
    onChangeSubscription = investmentClubRepository.onNewMessage.listen(
      (event) {
        emit(NewMessageState(event); // <-- The member "emit" can only be used within 'package:bloc/src/bloc.dart' or in test
      },
    );
  }

问题是 emit 不起作用(我收到警告 “成员“emit”只能在 'package:bloc/src/bloc.dart' 或测试中使用”)

bloc 如何监听流并根据流事件发出新状态?

您应该在 eventHandler 中使用 emit,使用以下代码完成您的任务:

abstract class Event {}

class DemoEvent extends Event {}

var fakeStream =
    Stream<int>.periodic(const Duration(seconds: 1), (x) => x).take(15);

class DemoBloc extends Bloc<Event, int> {
  DemoBloc() : super(0) {
    fakeStream.listen((_) {
      // add your event here
      add(DemoEvent());
    });
    on<DemoEvent>((_, emit) {
      // emit new state
      emit(state + 1);
    });
  }
}

你应该使用 emit.forEach( )
其中 forEach 必须 return 一个将被发射的状态

像这样

on<DemoEvent>((event, emit) async{
  await emit.forEach(
  investmentClubRepository.onNewMessage(),
  onData: (message){
  return yourState;
   });
});