FlutterBloc react to Blocs's initial state

Issue

How can I make my bloc react to the bloc’s initial state. In the example im trying to log something on the blocs initial state but nothing happens. It only prints the blocs constructor but not the print statement from facilityIntial


class FacilityBloc extends Bloc<FacilityEvent, FacilityState> {
  FacilityBloc(this.facilityRepository)
      : assert(facilityRepository != null),
        super(FacilityInitial()) {
    print('FacilitBlocConstructed');
  }

  final FacilityRepository facilityRepository;

  @override
  Stream<FacilityState> mapEventToState(
    FacilityEvent event,
  ) async* {
    print(event);
    if (event is FacilityGetAll) {
      yield* _mapGetAllFacilityToState(event);
    } else if (event is FacilityInitial) {
      print('Facility intial state');
    }
  }

  Stream<FacilityState> _mapGetAllFacilityToState(FacilityGetAll event) async* {
    yield FacilityLoading();
    try {
      List<Facility> facilities = await facilityRepository.loadAllFacility();
      yield FacilityLoaded(facilities);
    } on AppException catch (e) {
      yield FacilityError(e.exceptionMessageId);
    } catch (e) {
      yield FacilityError(LocaleKeys.generalError);
    }
  }
}

Solution

If FacilityInitial is a state, then it’s a reason why you couldn’t react to it in mapEventToState function (in this function you can react only to events, not states). If mapEventToState is an event (I can’t say for sure, cause you haven’t provided that info) it may conflict with the state class of the same name.

Also, you haven’t provided the code where you creating your bloc instance. To be able to react to events (even on initial events) you are to add this event to bloc. It could look like this:

BlocProvider<FacilityBloc>(
    lazy: false,
    create: (context) => FacilityBloc(FacilityRepository())..add(FacilityInitialEvent()),
  child: Text("My Text"),
)

In the example above I explicitly added FacilityInitialEvent, so to the bloc be able to handle it. Also, I’ve changed the event name a bit, to avoid name conflict.

Answered By – ChessMax

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.