繁体   English   中英

Bloc 如何监听 stream 并发出 state

[英]How can Bloc listen to stream and emit state

在我的 flutter 应用程序中,我使用flutter_bloc进行 state 管理。

有问题的bloc使用repository repository订阅 websocket,并将新数据添加到 stream。

问题:我的集团听 stream:

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不起作用(我收到警告“成员“发射”只能在 'package:bloc/src/bloc.dart' 或测试中使用”

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

你应该使用 emit.forEach( )
其中 forEach 必须返回一个 state ,它将被发出

像这样

await emit.forEach(yourStream, onData: (dynamic coming_data) {
  return your_state;
}).catchError((error) {
  emit error;
});

你应该在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);
    });
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM