Martin Pellicer
Martin Pellicer

Reputation: 129

Which is the correct way to await for an Event in Flutter Bloc

my application is growing in complexity and I can't figure out how to handle the await of an Event, when I need to execute code after that Event. Now I'm just putting the code that I need after an event inside the Bloc and I now that this is not the way to do it, making my app a mess. This is how I am managing my app:

For example, if I need to add a user in my backend and after that, execute an action I do this in my view/screen:

BlocProvider.of<UserBloc>(context).add(AddUserEvent())

As events are async, I can't put the code after that line so Inside the UserBloc I am making:

on<HomeNavigationEvent>((event, emit) {
  #Call backend api to create user
  
  #Do my needed action
});

And some times this is even worst because I need to call another Bloc, so I have to pass the context to that Event, like this:

BlocProvider.of<UserBloc>(context).add(AddUserEvent(context))

on<HomeNavigationEvent>((event, emit) {
  #Call backend api to create user
  
  BlocProvider.of<OtherBloc>(event.context).add(MyNeededActionEvent())
});

So I think the answer is related with Bloc listener, but I don't know how to check for an event instead of a state I mean I can't do this because I am receiving the state but not the Event:

return BlocListener<UserBloc, UserState>(
      listener: (context, state) {       #I would like to have (context, state, event))
        
 
        if (event is AddUserEvent) {
          #DO my needed action
        }
})

[EDITED]

Real case of my app:

VehiculoBloc() : super(const VehiculoState(vehicle: null)) {
    
        on<GetCurrentVehicle>((event, emit) async {
    
          vehicle = await api.getCurrentVehicle();
    
          final bool showVehicleButton = vehicle != null;
          BlocProvider.of<HomeBloc>(event.context).add(ShowVehicleButtonEvent(showVehicleButton ));
          
          emit(state.copyWith(vehicle: vehicle));
        });
    }

Upvotes: 3

Views: 7758

Answers (1)

Dr Younss AIT MOU
Dr Younss AIT MOU

Reputation: 1117

The main purpose of using BLoC is to separate the UI from the state. And have a global, and immutable, state that you can access from wherever you wish. The purpose of the UI is the fire events and let the BLoC generate the Appropriante state. If you try to listen to event, why would you even use BLoC? In situations like yours, you want to create a dedicated state for the AddUserEvent. For example AddUserStateSuccess Whenever the BLoC receives that event it will emit the corresponding state. All you have to do is listen for that state ;) In the listener of that state you can fire other events from other BLoC as well.

Upvotes: 4

Related Questions