简体   繁体   English

Flutter bloc 事件没有被调用

[英]Flutter bloc event not getting called

Event is getting called on button onPressed事件在按钮 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.版本flutter_bloc: ^8.0.1 ,如果可能的话,就想试试新版本。

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());
    }
  }
} 




  

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());
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM