[英]Flutter bloc event not getting called
事件在按鈕 onPressed 上被調用
BlocProvider.of<ProfileBloc>(context).add(FetchProfile());
我對集團狀態管理很陌生,請幫我解決這個問題。 版本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());
}
}
}
試試這樣:
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.