Learn how to create flutter firebase google auth repository. First we wanna have bunch of methods, that will help us to work with google firebase login and logout.
Here we included singUp, singIn, singInWithGoogle and singOut method. We need to create a class called AuthRepository.
First of all we get a FirebaseAuth.instance object. We will use this _firebaseAuth instance once we logout.
In other places we can just use FirebaseAuth.instance. This singleton object provides access to many convenient methods like createUserWithEmailAndPassword, signInWithEmailAndPassword
class AuthRepository {
final _firebaseAuth = FirebaseAuth.instance;
Future<void> signUp({required String email, required String password}) async {
try {
await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: email, password: password);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
throw Exception('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
throw Exception('The account already exists for that email.');
}
} catch (e) {
throw Exception(e.toString());
}
}
Future<void> signIn({
required String email,
required String password,
}) async {
try {
await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
throw Exception('No user found for that email.');
} else if (e.code == 'wrong-password') {
throw Exception('Wrong password provided for that user.');
}
}
}
Future<void> signInWithGoogle() async {
try {
final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();
final GoogleSignInAuthentication? googleAuth =
await googleUser?.authentication;
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth?.accessToken,
idToken: googleAuth?.idToken,
);
await FirebaseAuth.instance.signInWithCredential(credential);
} catch (e) {
throw Exception(e.toString());
}
}
Future<void> signOut() async {
try {
await _firebaseAuth.signOut();
} catch (e) {
throw Exception(e);
}
}
}