Home > Net >  How to save the user email and name in database while signing in with google?
How to save the user email and name in database while signing in with google?

Time:01-13

I am using google auth and i want to save user data in database...How can i get user details here and save it to database?

Future<void> signUpWithGoogle(
    BuildContext context,
    bool mounted,
  ) async {
    final googleSignIn = GoogleSignIn();
    final googleUser = await googleSignIn.signIn();
    if (googleUser == null) return;

    final googleAuth = await googleUser.authentication;

    final credential = GoogleAuthProvider.credential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );

    try {
      await FirebaseAuth.instance.signInWithCredential(credential);
       FirebaseFirestore.instance
          .collection('users')
          .doc(FirebaseAuth.instance.currentUser!.uid)
          .set({
        // 
      });
      if (mounted) return;
      InfoBox.show(context, InfoBox.success, "Signed In With Google");
    } on Exception catch (e) {
      if (mounted) return;
      InfoBox.show(context, InfoBox.success, e.toString());
    }
  }

CodePudding user response:

Please modify the code under your try block as below

try {
  final authResult = await FirebaseAuth.instance.signInWithCredential(credential);

  if (authResult.additionalUserInfo!.isNewUser) {
        await FirebaseFirestore.instance
            .collection('Users')
            .doc(authResult.user!.uid)
            .set({
          "Name": authResult.user!.displayName,
          "Email": authResult.user!.email,
        });
      }

  if (mounted) return;
  InfoBox.show(context, InfoBox.success, "Signed In With Google");

 
} on Exception catch (e) {
  if (mounted) return;
  InfoBox.show(context, InfoBox.success, e.toString());
}

Please accept the solution if it solves your problem

CodePudding user response:

Inside your try block, you have to get UserCredential which gives the User object data to be saved in the next line.

    try{
    UserCredential userCredential = await FirebaseAuth.instance.signInWithCredential(credential);
User user = userCredential.user; // User is updated version of FirebaseUser
FirebaseFirestore.instance.collection('users').doc(user.uid).set(/*Add Mapped User object*/);}
  • Related