Home > Blockchain >  flutter bloc calling an event in a class doesn't work
flutter bloc calling an event in a class doesn't work

Time:07-29

I have a class where I have to call an event from my bloc chat_bloc. Im not able to call the event, since I don't have any context. When I try to add the ChatBloc to my SocketRepository im totally lost here.. This is my class:

class SocketRepository {
  ...
  socket.on('receive_message', (jsonData) => {
  print('****** receive message called $jsonData'),
  // <- I need to call my chat_bloc event, but i don't have any context...
  
});
..

This is my ChatBloc which needs 2 parameters (minified important part):

class ChatBloc extends Bloc<ChatEvent, ChatState> {
  final DatabaseRepository _databaseRepository;
  final SocketRepository _socketRepository;
  
  ChatBloc(_databaseRepository, _socketRepository) : super(ChatInitial()) {
    on<LoadChat>((event, emit) async {

My best result i could achieve with the error I have:

class SocketRepository {
late ChatBloc chatbloc;
...
socket.on('receive_message', (jsonData) => {
chatbloc.add(ReceiveMessage()),
..

Unhandled Exception: LateInitializationError: Field 'chatbloc' has not been initialized.

I dont know how to inizialize it in a correct way..

CodePudding user response:

From the fragment you have shown it looks like you didn't initialize chatBot inSocketRepository. You have used late and didn't initalize it:

class SocketRepository {
late ChatBloc chatbloc; <--
...
socket.on('receive_message', (jsonData) => {
chatbloc.add(ReceiveMessage()),
..

Changing it to final and passing bloc to Repository would solve the issue but its BAD usage of Bloc.

The truth is Bloc should never be passed into repository.

If you want to communicate from the repository to Bloc, expose a stream on Repository and in the Bloc listen for the values in it:

class SocketRepository{

Stream<SocketMessages> get messages =>
      messagesStreamController.stream.asBroadcastStream();

and in Bloc constructor listen to the stream:

class ChatBloc extends Bloc<ChatEvent, ChatState> {
  final DatabaseRepository _databaseRepository;
  final SocketRepository _socketRepository;
  
  ChatBloc(_databaseRepository, _socketRepository) : super(ChatInitial()) {
    on<LoadChat>((event, emit) async {...}
    
  _socketRepository.messages.listen( (message) => 
    add(SocketMessageEmitted(message: message)));

This way you dont have circular dependency of SocketRepository injecting ChatBloc and ChatBloc injecting SocketRepository

  • Related