|
- import 'dart:async';
- import 'package:bloc/bloc.dart';
- import 'package:equatable/equatable.dart';
- import 'package:farm_tpf/data/repository/authentication_repository.dart';
- import 'package:farm_tpf/presentation/screens/login/models/password.dart';
- import 'package:farm_tpf/presentation/screens/login/models/username.dart';
- import 'package:farm_tpf/utils/pref.dart';
- import 'package:formz/formz.dart';
- import 'package:meta/meta.dart';
-
- part 'login_event.dart';
- part 'login_state.dart';
-
- class LoginBloc extends Bloc<LoginEvent, LoginState> {
- LoginBloc({
- @required AuthenticationRepository authenticationRepository,
- }) : assert(authenticationRepository != null),
- _authenticationRepository = authenticationRepository,
- super(const LoginState());
-
- final AuthenticationRepository _authenticationRepository;
- var pref = LocalPref();
-
- @override
- Stream<LoginState> mapEventToState(
- LoginEvent event,
- ) async* {
- if (event is LoginUsernameChanged) {
- yield _mapUsernameChangedToState(event, state);
- } else if (event is LoginPasswordChanged) {
- yield _mapPasswordChangedToState(event, state);
- } else if (event is LoginSubmitted) {
- yield* _mapLoginSubmittedToState(event, state);
- }
- }
-
- LoginState _mapUsernameChangedToState(
- LoginUsernameChanged event,
- LoginState state,
- ) {
- final username = Username.dirty(event.username);
- return state.copyWith(
- username: username,
- status: Formz.validate([state.password, username]),
- );
- }
-
- LoginState _mapPasswordChangedToState(
- LoginPasswordChanged event,
- LoginState state,
- ) {
- final password = Password.dirty(event.password);
- return state.copyWith(
- password: password,
- status: Formz.validate([password, state.username]),
- );
- }
-
- Stream<LoginState> _mapLoginSubmittedToState(
- LoginSubmitted event,
- LoginState state,
- ) async* {
- if (state.status.isValidated) {
- yield state.copyWith(status: FormzStatus.submissionInProgress);
- try {
- var user = await _authenticationRepository.signInWithCredentials(
- state.username.value,
- state.password.value,
- );
- var token = user.idToken;
- pref.saveString(DATA_CONST.TOKEN_KEY, token);
- int currentTime = DateTime.now().millisecondsSinceEpoch;
- pref.saveString(DATA_CONST.EXPIRED_TIME, currentTime.toString());
-
- yield state.copyWith(status: FormzStatus.submissionSuccess);
- } on Exception catch (_) {
- yield state.copyWith(status: FormzStatus.submissionFailure);
- }
- }
- }
- }
|