-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlogin_bloc.dart
67 lines (60 loc) · 2.14 KB
/
login_bloc.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import 'package:bloc/bloc.dart';
import 'package:formz/formz.dart';
import 'package:flutter_cbl_learning_path/features/login/models/password.dart';
import 'package:flutter_cbl_learning_path/features/login/models/username.dart';
import 'package:flutter_cbl_learning_path/features/login/bloc/bloc.dart';
import 'package:flutter_cbl_learning_path/features/router/route.dart';
class LoginBloc extends Bloc<LoginEvent, LoginState> {
final FakeAuthenticationService _authenticationService;
LoginBloc({required FakeAuthenticationService authenticationService})
: _authenticationService = authenticationService,
super(const LoginState()) {
on<LoginUsernameChanged>(_onUsernameChanged);
on<LoginPasswordChanged>(_onPasswordChanged);
on<LoginSubmitted>(_onSubmitted);
on<LogoutSubmitted>(_onLogoutSubmitted);
}
void _onUsernameChanged(
LoginUsernameChanged event, Emitter<LoginState> emit) {
final username = Username.dirty(event.username);
emit(
state.copyWith(
username: username,
status: Formz.validate([state.password, username]),
),
);
}
void _onPasswordChanged(
LoginPasswordChanged event, Emitter<LoginState> emit) {
final password = Password.dirty(event.password);
emit(
state.copyWith(
password: password,
status: Formz.validate([password, state.username]),
),
);
}
void _onLogoutSubmitted(LogoutSubmitted event, Emitter<LoginState> emit) {
_authenticationService.signOut();
}
Future<void> _onSubmitted(
LoginSubmitted event,
Emitter<LoginState> emit,
) async {
if (state.status.isValidated) {
emit(state.copyWith(status: FormzStatus.submissionInProgress));
try {
var result = await _authenticationService.authenticateUser(
username: state.username.value,
password: state.password.value,
);
if (!result) {
emit(state.copyWith(status: FormzStatus.submissionFailure));
}
emit(state.copyWith(status: FormzStatus.submissionSuccess));
} catch (_) {
emit(state.copyWith(status: FormzStatus.submissionFailure));
}
}
}
}