import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pooling_apps/data/repositories/auth_repository.dart';
import 'package:pooling_apps/models/user_model.dart';
import 'auth_event.dart';
import 'auth_state.dart';
class AuthBloc extends Bloc<AuthEvent, AuthState> {
final AuthRepository authRepository;
AuthBloc({required this.authRepository}) : super(AuthInitial());
Stream<AuthState> mapEventToState(AuthEvent event) async* {
if (event is LoginEvent) {
yield AuthLoading();
try {
final UserModel? user =
await authRepository.login(event.username, event.password);
yield AuthAuthenticated(user: user!);
} catch (e) {
yield AuthError(message: e.toString());
}
}
}
}
I’m trying to implement the BLoC pattern for state management in my Flutter application, specifically for a login feature. I have set up the basic structure but am encountering some issues with managing state and handling authentication properly. I would appreciate any guidance or suggestions on best practices for structuring my BLoC and how to handle login events and states effectively.
If you want to uase BLoC pattern as state managment and flutter_bloc as an implementation of BLoC pattern, then you should use the latest version. As you can see here
In bloc v8.0.0, all previously deprecated APIs were removed.
- mapEventToState removed in favor of on
...
So you should do now something like this:
class AuthBloc extends Bloc<AuthEvent, AuthState> {
AuthBloc({required AuthRepository authRepository})
: _authRepository = authRepository,
super(AuthInitial()) {
on<LoginEvent>(_onLoginEvent);
}
final AuthRepository _authRepository;
Future<void> _onLoginEvent(LoginEvent event, Emitter<AuthState> emit) async {
try {
emit(AuthLoading());
final user = await _authRepository.login(event.username, event.password);
emit(
user == null
? const AuthError(message: 'User not exist')
: AuthAuthenticated(user: user),
);
} catch (e) {
emit(AuthError(message: e.toString()));
}
}
}