How to fix this error: StateError (Bad state: add(SignUp Button Pressed) was called without a registered event handler. Make sure to register a handler via on((event, emit) {...}))
SignUpBloc:
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import '../../domain/repositories/user_repository.dart';
part 'sign_up_event.dart';
part 'sign_up_state.dart';
class SignUpBloc extends Bloc<SignUpEvent, SignUpState> {
final UserRepository userRepository;
SignUpBloc({required this.userRepository}) : super(SignUpInitial());
@override
Stream<SignUpState> mapEventToState(SignUpEvent event) async* {
if (event is SignUpButtonPressed) {
yield SignUpLoading();
try {
final email = event.email;
final password = event.password;
final result = await userRepository.registerUser(email, password);
yield result.fold(
(failure) => SignUpError(message: failure.toString()),
(user) => SignUpSuccess(email: user.email),
);
} catch (error) {
yield SignUpError(message: error.toString());
}
}
}
}
I have another way to use bloc based on your error handler via on((event, emit) {...}))
.
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import '../../domain/repositories/user_repository.dart';
part 'sign_up_event.dart';
part 'sign_up_state.dart';
class SignUpBloc extends Bloc<SignUpEvent, SignUpState> {
final UserRepository userRepository;
SignUpBloc({required this.userRepository}) : super(SignUpInitial());
on<SignUpEvent>((event, emit) async {
emit(SignUpLoading());
try {
final email = event.email;
final password = event.password;
final result = await userRepository.registerUser(email, password);
await result.fold(
(failure) async => emit(SignUpError(message: failure.toString())),
(user) async => emit(SignUpSuccess(email: user.email),
));
} catch (error) {
emit(SignUpError(message: error.toString()));
}
});
}
Please understand the concept of bloc. Bloc has 3 files, event || bloc || state
.
emit()
.