Untitled

 avatar
unknown
dart
a year ago
2.3 kB
10
Indexable
// auth_event.dart
abstract class AuthEvent {}

class LoginRequested extends AuthEvent {
  final String username;
  final String password;

  LoginRequested(this.username, this.password);
}

class LogoutRequested extends AuthEvent {}


//////////////////////////////////////////////////

// auth_state.dart
abstract class AuthState {}

class AuthInitial extends AuthState {}        // app just started
class AuthLoading extends AuthState {}        // during login
class Authenticated extends AuthState {       // logged in
  final String username;
  Authenticated(this.username);
}
class Unauthenticated extends AuthState {}    // logged out or failed login
class AuthFailure extends AuthState {
  final String error;
  AuthFailure(this.error);
}


///////////////////////////////////////////////

// auth_bloc.dart
import 'package:flutter_bloc/flutter_bloc.dart';
import 'auth_event.dart';
import 'auth_state.dart';
import 'auth_repository.dart';

class AuthBloc extends Bloc<AuthEvent, AuthState> {
  final AuthRepository repository;

  AuthBloc(this.repository) : super(AuthInitial()) {
    // 🔹 Handle LoginRequested inline
    on<LoginRequested>((event, emit) async {
      print("AuthBloc: LoginRequested with username=${event.username} (password hidden)");

      emit(AuthLoading());
      try {
        final success = await repository.login(event.username, event.password);

        if (success) {
          print("AuthBloc: Login success for ${event.username}");
          emit(Authenticated(event.username));
        } else {
          print("AuthBloc: Invalid credentials");
          emit(AuthFailure("Invalid username or password"));
          emit(Unauthenticated());
        }
      } catch (e) {
        print("AuthBloc: Exception during login: $e");
        emit(AuthFailure("Login failed. Please try again."));
        emit(Unauthenticated());
      }
    });

    // 🔹 Handle LogoutRequested inline
    on<LogoutRequested>((event, emit) async {
      print("AuthBloc: LogoutRequested");

      emit(AuthLoading());
      try {
        await repository.logout();
        print("AuthBloc: Logout success");
      } catch (e) {
        print("AuthBloc: Exception during logout: $e");
      }
      emit(Unauthenticated());
    });
  }
}
Editor is loading...
Leave a Comment