5

i have worked with google sign in and email/password providers of firebase auth and i note that i colud use sign in in google_sign_in provider with the same email after i sign up with email/password provider and also sign out after sign email up so i could go to authscreen as my , but when i tried the Reverse after with another account after i use google_sign_in and signout from google and tried to sign up it give me error email is already exists and when i tried to login it give me error the password is wrong even thought i write password of google email 100% right, so is there a way to enable to sign
here is photo the error shown in snackbar of login
and here is sign up error
and this is the two emails in firebase auth

code of choice_provier_screen

  import 'package:firebase_auth/firebase_auth.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter_app/tabs.dart';
    import './signInOrLogIn_Screen.dart';
    import 'package:google_sign_in/google_sign_in.dart';

    Future<UserCredential> signinWithGoogle() async {
        final GoogleSignInAccount googleuser = await GoogleSignIn().signIn();
        final GoogleSignInAuthentication googleauth = await googleuser.authentication;
        final GoogleAuthCredential credential = GoogleAuthProvider.credential(
        accessToken: googleauth.accessToken,
    idToken: googleauth.idToken,
  );
  return await FirebaseAuth.instance.signInWithCredential(credential);
}

Widget createRaised(
    {Color backgroundcolor,
    String image,
    String name,
    Color textcolor,
    Function f}) {
  return SizedBox(
    width: 290,
    child: RaisedButton.icon(
      onPressed: f,
      label: Text(
        name,
        style: TextStyle(fontSize: 18, color: textcolor),
      ),
      icon: Padding(
        padding: const EdgeInsets.only(right: 10),
        child: Image.asset(
          image,
          height: 20,
          fit: BoxFit.fill,
        ),
      ),
      padding: EdgeInsets.all(10),
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(30),
          side: BorderSide(color: Colors.black)),
      color: backgroundcolor,
      splashColor: Colors.transparent,
      highlightColor: Colors.transparent,
    ),
  );
}

    class ChoiceAuthMehod extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                SizedBox(
                  width: 290,
                  child: RaisedButton(
                    color: Colors.black,
                    child: Text(
                      'Sign up / log in',
                      style: TextStyle(color: Colors.red, fontSize: 18),
                    ),
                    onPressed: () {
                      Navigator.of(context)
                          .pushReplacementNamed(AuthScreen.routeName);
                    },
                    padding: EdgeInsets.all(10),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(30),
                        side: BorderSide(color: Colors.black)),
                  ),
                ),
                SizedBox(
                  height: 10,
                ),
                createRaised(
                    backgroundcolor: Colors.white,
                    image: 'lib/google_transperant.png',
                    name: 'sign up with google',
                    f: () => signinWithGoogle().then((value) {
                          print('email google : ${value.user.displayName}');
                          Navigator.of(context)
                              .pushReplacementNamed(Tabs.routeName);
                        }),
                    textcolor: Colors.black),
              ],
            ),
          ),
        );
      }
    }

code for signin/login
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_app/checkuserstate.dart';
import './textfiledform.dart';

class AuthScreen extends StatefulWidget {
  static const routeName ='/Auth-screen';
  @override
  _AuthScreenState createState() => _AuthScreenState();
}

class _AuthScreenState extends State<AuthScreen> {
  final _formKey = GlobalKey<FormState>();
  final _scaffoldKey = GlobalKey<ScaffoldState>();

  // if false login else will change to sign in when user hit the signUp button
  bool changeAuthMode = false;

  bool autoError = false;
  String email ;
  FocusNode emailNode = FocusNode(), pNode = FocusNode(), cpNode = FocusNode();
  bool _loading = false;
  final _passwordController = TextEditingController();

  void changeInputState() {
    setState(() {
      changeAuthMode = !changeAuthMode;
    });
  }

  void createSnackBar(String e) {
    _scaffoldKey.currentState.removeCurrentSnackBar();
    _scaffoldKey.currentState.showSnackBar(SnackBar(
      content: Text(e),
      backgroundColor: Colors.red,
      action: SnackBarAction(
        label: 'ok',
        onPressed: () {},
      ),
    ),
    );
  }

  Future<String> signUp(String er) async {
    try {
      var result = await FirebaseAuth.instance.createUserWithEmailAndPassword(
          email: email, password: _passwordController.text);
      await result.user.sendEmailVerification().then((_)  {
         result.user.reload().then((value) => Navigator.pushReplacementNamed(
          context,
          CheckUserState.routeName,
        ));
      });
    } on FirebaseAuthException catch (e) {
      if (e.code == 'weak-password') {
        er = 'The password provided is too weak.';
      } else if (e.code == 'email-already-in-use') {
        er = 'The account already exists for that email.';
      }
    } catch (e) {
      er = e.toString();
    }
    return er;
  }

  Future<String> login(String er) async {
    try {
      await FirebaseAuth.instance
          .signInWithEmailAndPassword(
          email: email, password: _passwordController.text)
          .then((value) {

        print('login page = ${FirebaseAuth.instance.currentUser.emailVerified}');

          Navigator.of(context).pushReplacementNamed(CheckUserState.routeName);});
      //if not did return / navigator or set error ='' the error will have the old error text and will show the snackBarError even if email & pw correct
    } on FirebaseAuthException catch (e) {
      if (e.code == 'user-not-found') {
        er =
        'No user found for that email,this email is not exist please sign up';
      } else if (e.code == 'wrong-password') {
        er = 'Wrong password provided for that user.';
      }
    } catch (e) {
      er = e.toString();
    }
    return er;
  }

  void submit() async {
    _loading = true;
    String er;
    if (!_formKey.currentState.validate()) {
      autoError = true;
      _loading = false;
      return;
    }
    _formKey.currentState.save();
    if (changeAuthMode) {
      er = await signUp(er);
    } else {
      er = await login(er);
    }
    if (er != null) createSnackBar(er);
    setState(() {
      _loading = false;
    });
  }

  @override
  void dispose() {
    emailNode.dispose();
    pNode.dispose();
    cpNode.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      backgroundColor: Colors.black,
      body:
        Card(
          margin: const EdgeInsets.all(30),
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10)),
          child: Container(
            padding: EdgeInsets.all(16.0),
            child: Form(
              autovalidate: autoError,
              key: _formKey,
              child: SingleChildScrollView(
                child: Column(
                  children: <Widget>[
                    CustomTextForm(
                      label: 'Email',
                      inputType: TextInputType.emailAddress,
                      inputAction: TextInputAction.next,
                      node: emailNode,
                      onSubmit: (_) =>
                          FocusScope.of(context).requestFocus(pNode),
                      onSaved: (value) {
                        email = value;
                      },
                      icon: Icon(Icons.email),
                      obscureTextVar: false,
                      validateVar: (value) {
                        if (value.isEmpty)
                          return "please enter your email";
                        RegExp pattern = new RegExp(
                            r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$');
                        if (!pattern.hasMatch(value))
                          return 'in valid email';
                        return null;
                      },
                    ),
                    CustomTextForm(
                      label: 'password',
                      obscureTextVar: true,
                      inputType: TextInputType.visiblePassword,
                      validateVar: (value) => value.isEmpty
                          ? "please enter your password"
                          : null,
                      icon: Icon(Icons.vpn_key),
                      controller: _passwordController,
                      inputAction: changeAuthMode
                          ? TextInputAction.next
                          : TextInputAction.done,
                      node: pNode,
                      onSubmit: (_) {
                        changeAuthMode?
                          FocusScope.of(context).requestFocus(cpNode):
                          submit();
                      }
                    ),
                    if (changeAuthMode)
                      CustomTextForm(
                        node: cpNode,
                        label: 'Conform password',
                        inputType: TextInputType.visiblePassword,
                        icon: Icon(Icons.vpn_key),
                        validateVar: (value) => value.isEmpty
                            ? "please enter your password"
                            : value != _passwordController.text
                            ? 'password not matches'
                            : null,
                        obscureTextVar: true,
                        inputAction: TextInputAction.done,
                        onSubmit: (_) => submit(),
                      ),
                    SizedBox(
                      height: 4,
                    ),
                    !_loading
                        ? RaisedButton(
                      color: Colors.black,
                      splashColor: Colors.white,
                      child: Text(
                          !changeAuthMode ? 'Log in' : 'sign up'),
                      onPressed: () => submit(),
                    )
                        : CircularProgressIndicator(),
                    FlatButton(
                        onPressed: changeInputState,
                        child: Text(
                            '${!changeAuthMode ? 'signUp' : 'logIn'} instead')),
                  ],
                ),
              ),
            ),
          ),
        ),
    );
  }
}

notice

i already search for my problem and i found only this question which look very similar to my question but with none solution to it. Why can't I link firebase email-password sign-in to google sign-in?

amr q
  • 51
  • 3
  • If your user signs in with Google, after having already manually registered an account, their authentication provider will automatically change to Google, due to the Firebase Authentications concept of trusted providers. You can find out more about this [here](https://groups.google.com/g/firebase-talk/c/ms_NVQem_Cw/m/8g7BFk1IAAAJ). – Zohaib Tariq Feb 18 '21 at 11:59
  • A related question is here: https://stackoverflow.com/a/66453429/233382 – chongman Dec 02 '21 at 06:30

2 Answers2

0

Go to Firebase console Authentication > Sign-in Method > Advanced Change it to Multiple accounts per email address..

You can now login with same email address for different providers

Deva
  • 23
  • 3
0

See the answers and longer description here:

Firebase Auth link provider Google sign in issue?

The short answer is Trusted vs Untrusted providers.

chongman
  • 2,447
  • 4
  • 21
  • 23