skip to Main Content

I am implementing Google sign-in with firebase auth and also storing the corresponding user information in Cloud Firestore and Shared Preferences. On running the app on my phone and tapping the sign-in/sign-up button, the pop with the available accounts appears. But when I select the desired Google account, the pop-up disappears and an error occurs as follows:

[firebase_auth/network-request-failed] A network error (such as timeout, interrupted connection or unreachable host) has occurred.

Also, no account and user details are stored neither in the Cloud Firestore console nor in the Users section of Firebase Auth.
But the details are stored in shared preferences and are able to navigate to HomePage directly when I re-run the application.My code is:

class Login extends StatefulWidget {
  static final String id = 'login_screen';
  const Login({Key? key}) : super(key: key);

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  final GoogleSignIn googleSignIn = new GoogleSignIn();
  final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
  late SharedPreferences preferences;
  bool loading = false;
  bool isLoggedIn = false;
  User? user;
  @override
  void initState() {
    super.initState();
    isSignedIn();
  }

  void isSignedIn() async {
    setState(() {
      // loading = true;
    });
    preferences = await SharedPreferences.getInstance();
    isLoggedIn = await googleSignIn.isSignedIn(); //Check if user is signed in

    if (isLoggedIn) {
      Navigator.pushReplacement(
          context,
          MaterialPageRoute(
              builder: (context) =>
                  HomePage())); //Helps us to keep user logged in once he has logged in so that user doesn't come to log in screen again on pressing back.
      setState(() {
        loading = false;
      });
    }
  }

  Future signInWithGoogle() async {
    preferences = await SharedPreferences.getInstance();
    setState(() {
      loading = true;
    });
    GoogleSignInAccount? googleUser = await googleSignIn.signIn();

    if (googleUser != null) {
     final GoogleSignInAuthentication googleSignInAuthentication =
          await googleUser.authentication;

      final AuthCredential credential = GoogleAuthProvider.credential(
        accessToken: googleSignInAuthentication.accessToken,
        idToken: googleSignInAuthentication.idToken,
      );
      final UserCredential userCredential =
          await firebaseAuth.signInWithCredential(credential);
      user = userCredential.user;
      if (user != null) {
        final QuerySnapshot result = await FirebaseFirestore.instance
            .collection("users")
            .where("id", isEqualTo: user?.uid)
            .get();
        //Check whether the id of that field is equal to the id of the user we obtained above.
        //If we have it, it means the user is already signed up to the application.
        final List<DocumentSnapshot> docs = result.docs;
        if (docs.length ==
            0) //If the docs are empty means that user does not exist in our database, therfore sign hom up
        {
          //Add user to our collection
          FirebaseFirestore.instance.collection("users").doc(user?.uid).set({
            "id": user?.uid,
            "username": user?.displayName,
            "profilePicture": user?.photoURL,
            "phNo": user?.phoneNumber,
            "email": user?.email,
          });
          await preferences.setString('id', user!.uid);
          await preferences.setString('userName', user!.displayName ?? ' ');
          await preferences.setString('photoUrl', user!.photoURL ?? ' ');
          await preferences.setString('email', user!.email ?? '');
        } else {
          await preferences.setString('id', docs[0]['id']);
          await preferences.setString('userName', docs[0]['username']);
          await preferences.setString('photoUrl', docs[0]['photoUrl']);
          await preferences.setString('email', docs[0]['email']);
        }
        Navigator.popAndPushNamed(context, HomePage.id);
        setState(() {
          loading = false;
        });

      } else {}

      
    }
  }

 

3

Answers


  1. This may be due to your Internet connectivity

    ☑️ Make sure your phone or emulator has access to internet

    ☑️ Also make sure that you have added the ACCESS_INTERNET permission to your app in the AndroidManifest.xml file

    Login or Signup to reply.
  2. Have you added SHA certificate fingerprints in firebase project settings?
    Not adding SHA might cause this issue.

    Login or Signup to reply.
  3. struggled with this error for several hours and got every single solution that people pointed.

    One of them finally solved my problem. I’m not sure which one will solve yours, so try everything.

    1. Deactivate your emulators (Close the terminal holding your local hosts),
    2. Get the button out of a form tag, prefer div tag
    3. Get the button out of a submit type,
    4. Add this piece of code for your button don’t bubble:
    5. If you’re indeed testing on localhost, prefer 127.0.0.1/ to localhost/
    document.getElementById('signup-btn').addEventListener('click', function(event){
        event.preventDefault()
    1. If you are using the "HTTPS Everywhere" extension, then go to the "HTTPS Everywhere" settings and click on the "Disable HTTPS Everywhere for this site" button. It helped me.

    2. Disable CORS Chrome plugin

    3. Make sure you’re passing actual values instead of the reference to the button

    4. prefer testing on chrome instead of edge.

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