Ad
How Can Bloc Listen To Stream And Emit State
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?
Ad
Answer
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);
});
}
}
Ad
source: stackoverflow.com
Related Questions
- → How do you create a 12 or 24 mnemonics code for multiple cryptocurrencies (ETH, BTC and so on..)
- → Flutter: input text field don't work properly in a simple example..... where am I wrong?
- → Can I customize the code formatting of Dart code in Atom?
- → Is it possible to develop iOS apps with Flutter on a Linux virtual machine?
- → Display SnackBar in Flutter
- → JSON ObjectMapper in Flutter
- → Material flutter app source code
- → TabBarSelection No such method error
- → How do I set the animation color of a LinearProgressIndicator?
- → Add different routes/screens to Flutter app
- → Is there a way to get the size of an existing widget?
- → How to share a file using flutter
- → Is there an easy way to find particular text built from RichText in a Flutter test?
Ad