Flutter - Sign-In with Google doesn't works for the 2nd Sign-in

226 Views Asked by At

I am working on Sign-in with Google. The code below is reproducible.

When I sign in with Google, it works perfectly for the 1st time sign-in. But it is stuck. I put "print()" with 1-4 to see how it goes (see the code below). The console shows below:

flutter: 1

then the "Continue or Cancel" pops up. If "Continue" is clicked.

flutter: 2
flutter: 3
flutter: 4

Then I sign out and sign in again, it's stuck in "2" and shows me the CircularProgressIndicator. The console shows below:

flutter: 1
flutter: 2 => Stuck here.

To make sure, I check user sign In status in Init() with the code below. It looks fine.

My questions: a. Why does the 2nd sign-in attempt proceed to "3" directly, which is different from the 1st sign-in attempt ("1", "Pop UP", then "2", "3", "4").

<------- Sign In Page ---------->
import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:Config/designConfig.dart';
import 'package:CustomWidgetMethod/customCircularProgressIndicator.dart';

// Sign In with Google
GoogleSignIn _googleSignIn = GoogleSignIn(
  scopes: [
    'email',
    'https://www.googleapis.com/auth/contacts.readonly',
  ],
);

class SignInTest extends StatefulWidget {
  @override
  _SignInTestState createState() => _SignInTestState();
}

class _SignInTestState extends State<SignInTest> {
  // FirstBase
  final FirebaseAuth _auth = FirebaseAuth.instance;

  //Google Sign in
  Future<UserCredential> _signInWithGoogle() async {
    print('1');
    final GoogleSignInAccount? googleSignInAccount =
        await _googleSignIn.signIn();
    print('2');
    final GoogleSignInAuthentication? googleSignInAuthentication =
        await googleSignInAccount?.authentication;
    print('3');
    final AuthCredential authCredential = GoogleAuthProvider.credential(
        idToken: googleSignInAuthentication?.idToken,
        accessToken: googleSignInAuthentication?.accessToken);
    print('4');
    return await _auth.signInWithCredential(authCredential);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              padding: const EdgeInsets.symmetric(
                  horizontal: DesignConfig.pagePadding),
              // color: Colors.white,
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      SizedBox(
                        width: DesignConfig.elevatedButtonHeight,
                        height: DesignConfig.elevatedButtonHeight,
                        child: InkWell(
                          onTap: () {
                            customCircularProgressIndicator(context);
                            _signInWithGoogle()
                                .then((UserCredential userCredential) {
                              Navigator.of(context).pop();
                              if (userCredential.user!.uid.isNotEmpty) {
                                Navigator.of(context)
                                    .pushNamed('/GoogleSignTest');
                              } else {
                                Navigator.of(context).pop();
                              }
                            });
                          },
                          child: CircleAvatar(
                              radius: 45.0,
                              backgroundColor: Colors.grey[200],
                              child: Image.asset(
                                'assets/images/google_login.png',
                                height: 20,
                                width: 20,
                              )),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}


<------- Sign Out Page ---------->

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';

class GoogleSignTest extends StatefulWidget {
  const GoogleSignTest({Key? key}) : super(key: key);

  @override
  _GoogleSignTestState createState() => _GoogleSignTestState();
}

class _GoogleSignTestState extends State<GoogleSignTest> {
 
  final GoogleSignIn _googleSignIn = GoogleSignIn();

  Future<void> _signOut() async {
    FirebaseAuth _auth = FirebaseAuth.instance;
    try {
      await _auth.signOut();
      await _googleSignIn.disconnect();
      await _googleSignIn.currentUser?.clearAuthCache();
    } catch (error) {
      print('error: $error');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Google Sign In Test'),
      ),
      body: Center(
        child: Column(
          children: [
            ElevatedButton(
                onPressed: () {
                  _signOut().then((value) async {
                    Navigator.of(context).pop();
                  });
                },
                child: Text("Sign Out"))
          ],
        ),
      ),
    );
  }
}


0

There are 0 best solutions below