|
1 | 1 | import 'package:firebase_auth/firebase_auth.dart'; |
2 | 2 | import 'package:flutter/material.dart'; |
| 3 | +import 'package:awesome_dialog/awesome_dialog.dart'; |
3 | 4 | import 'package:google_sign_in/google_sign_in.dart'; |
4 | 5 | import 'extensions.dart'; |
5 | 6 | import '../routing/routes.dart'; |
6 | 7 |
|
7 | 8 | class GoogleSignin { |
| 9 | + static final _auth = FirebaseAuth.instance; |
| 10 | + |
8 | 11 | static Future signInWithGoogle(BuildContext context) async { |
9 | | - // Trigger the authentication flow |
10 | | - final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn(); |
11 | | - if (googleUser == null) { |
12 | | - return; |
13 | | - } |
14 | | - // Obtain the auth details from the request |
15 | | - final GoogleSignInAuthentication googleAuth = |
16 | | - await googleUser.authentication; |
| 12 | + try { |
| 13 | + // Trigger the authentication flow |
| 14 | + final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn(); |
| 15 | + if (googleUser == null) { |
| 16 | + return; |
| 17 | + } |
| 18 | + |
| 19 | + // Obtain the auth details from the request |
| 20 | + final GoogleSignInAuthentication googleAuth = |
| 21 | + await googleUser.authentication; |
17 | 22 |
|
18 | | - // Create a new credential |
19 | | - final credential = GoogleAuthProvider.credential( |
20 | | - accessToken: googleAuth.accessToken, |
21 | | - idToken: googleAuth.idToken, |
22 | | - ); |
23 | | - // Once signed in, return the UserCredential |
24 | | - await FirebaseAuth.instance.signInWithCredential(credential); |
25 | | - if (!context.mounted) return; |
26 | | - context.pushNamedAndRemoveUntil( |
27 | | - Routes.homeScreen, |
28 | | - predicate: (route) => false, |
29 | | - ); |
| 23 | + // Create a new credential |
| 24 | + final credential = GoogleAuthProvider.credential( |
| 25 | + accessToken: googleAuth.accessToken, |
| 26 | + idToken: googleAuth.idToken, |
| 27 | + ); |
| 28 | + |
| 29 | + final UserCredential authResult = |
| 30 | + await _auth.signInWithCredential(credential); |
| 31 | + |
| 32 | + if (authResult.additionalUserInfo!.isNewUser) { |
| 33 | + await _auth.currentUser!.delete(); |
| 34 | + if (!context.mounted) return; |
| 35 | + context.pushNamedAndRemoveUntil( |
| 36 | + Routes.createPassword, |
| 37 | + predicate: (route) => false, |
| 38 | + arguments: [googleUser, credential], |
| 39 | + ); |
| 40 | + } else { |
| 41 | + if (!context.mounted) return; |
| 42 | + context.pushNamedAndRemoveUntil( |
| 43 | + Routes.homeScreen, |
| 44 | + predicate: (route) => false, |
| 45 | + ); |
| 46 | + } |
| 47 | + } catch (e) { |
| 48 | + await AwesomeDialog( |
| 49 | + context: context, |
| 50 | + dialogType: DialogType.info, |
| 51 | + animType: AnimType.rightSlide, |
| 52 | + title: 'Sign in error', |
| 53 | + desc: e.toString(), |
| 54 | + ).show(); |
| 55 | + } |
30 | 56 | } |
31 | 57 | } |
0 commit comments