skip to Main Content

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());
    }
  }

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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*/);}
    

    You can use user object to get all the necessary data.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search