-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsign_in_view_bloc.dart
78 lines (74 loc) · 2.78 KB
/
sign_in_view_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
68
69
70
71
72
73
74
75
76
77
78
import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart' as firebase_auth;
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:injectable/injectable.dart';
import 'package:projectunity/data/services/account_service.dart';
import '../../../data/core/exception/error_const.dart';
import '../../../data/model/account/account.dart';
import '../../../data/provider/user_state.dart';
import '../../../data/services/auth_service.dart';
import 'sign_in_view_event.dart';
import 'sign_in_view_state.dart';
@Injectable()
class SignInBloc extends Bloc<SignInEvent, SignInState> {
final UserStateNotifier _userStateNotifier;
final AuthService _authService;
final AccountService _accountService;
SignInBloc(
this._userStateNotifier,
this._authService,
this._accountService,
) : super(const SignInState()) {
on<GoogleSignInEvent>(_googleSignIn);
on<AppleSignInEvent>(_appleSignIn);
}
Future<void> _googleSignIn(
SignInEvent event, Emitter<SignInState> emit) async {
try {
emit(state.copyWith(googleSignInLoading: true));
firebase_auth.User? authUser = await _authService.signInWithGoogle();
if (authUser != null) {
final Account user = await _accountService.getUser(authUser);
await _userStateNotifier.setUser(user);
emit(state.copyWith(googleSignInLoading: false, signInSuccess: true));
} else {
emit(state.copyWith(googleSignInLoading: false));
}
} catch(e) {
emit(state.copyWith(
googleSignInLoading: false, error: firesbaseAuthError));
}
}
Future<void> _appleSignIn(
AppleSignInEvent event, Emitter<SignInState> emit) async {
try {
emit(state.copyWith(appleSignInLoading: true));
firebase_auth.User? authUser = await _authService.signInWithApple();
if (authUser != null) {
final Account? user = await _accountService.getAppleUser(authUser);
if (user == null) {
emit(state.copyWith(
appleSignInLoading: false,
error: appleSigninError,
firebaseAuthUser: authUser));
return;
}
await _userStateNotifier.setUser(user);
emit(state.copyWith(appleSignInLoading: false, signInSuccess: true));
} else {
emit(state.copyWith(appleSignInLoading: false));
}
} catch (e, stack) {
if (e is FirebaseAuthException && e.code == 'canceled') {
emit(state.copyWith(appleSignInLoading: false));
return;
}
FirebaseCrashlytics.instance
.recordError(e, stack, reason: 'Apple Sign In Error');
emit(state.copyWith(
appleSignInLoading: false, error: somethingWentWrongError));
}
}
}