In my flutter app, I use flutter_bloc for state management.
The bloc in question uses a repository. The repository subscribes to a websocket, and new data is added to a stream.
Problem: My bloc listens to the 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
},
);
}
The problem is that emit does not work (I get the warning "The member "emit" can only be used within 'package:bloc/src/bloc.dart' or in test")
How can bloc listen to a stream and emit new states depending on stream events?
You should use emit in eventHandler, use below code to complete your task:
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);
});
}
}
you should use emit.forEach( )
where forEach must return a state which will be emitted
like this
await emit.forEach(yourStream, onData: (dynamic coming_data) {
return your_state;
}).catchError((error) {
emit error;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With