Home > Mobile >  Flutter bloc event not getting called
Flutter bloc event not getting called

Time:07-14

Event is getting called on button onPressed

BlocProvider.of<ProfileBloc>(context).add(FetchProfile());

I am very new to bloc state management, please help me with this issue. version flutter_bloc: ^8.0.1, just wanna try if its possible with the newer version.

class ProfileBloc extends Bloc<ProfileEvent, ProfileState> {
  AuthRepo authRepo;
  @override
  ProfileBloc(ProfileState initialState, {required this.authRepo})
      : super(ProfileLoading()) {
    on<FetchProfile>((event, emit) async {
      return await fetchProfileEvent(event, emit);
    });
  }

  Future<void> fetchProfileEvent(
      FetchProfile event, Emitter<ProfileState> emit) async {
    log("$event", name: "eventToState");

    emit(ProfileLoading());
    try {
      await authRepo.getProfileCall().then(
        (value) {
          log("$value", name: 'FetchProfile');
          if (value != 'failed') {
            emit(ProfileLoaded(userData: userProfileModelFromJson(value)));
          } else {
            emit(ProfileLoaded(userData: null));
          }
        },
      );
    } catch (e) {
      log("$e", name: "ProfileBloc : FetchProfile");
      emit(ProfileError());
    }
  }
} 




  

CodePudding user response:

Try it like this:

class ProfileBloc extends Bloc<ProfileEvent, ProfileState> {
  AuthRepo authRepo;
  @override
  ProfileBloc({required this.authRepo})
      : super(ProfileLoading()) {
    on<FetchProfile>(fetchProfileEvent);
  }

  Future<void> fetchProfileEvent(
      FetchProfile event, Emitter<ProfileState> emit) async {
    log("$event", name: "eventToState");

    emit(ProfileLoading());
    try {
      final value = await authRepo.getProfileCall();
      log("$value", name: 'FetchProfile');
      if (value != 'failed') {
        emit(ProfileLoaded(userData: userProfileModelFromJson(value)));
      } else {
        emit(ProfileLoaded(userData: null));
      }
    } catch (e) {
      log("$e", name: "ProfileBloc : FetchProfile");
      emit(ProfileError());
    }
  }
}
  • Related