Esraa Hamada
Esraa Hamada

Reputation: 179

Inability to get user data when returning to the application after logging in with Google

I used this code to sign in with google

GoogleSignIn googleSignIn = GoogleSignIn();
    try{
      await googleSignIn.signIn();
    }on Exception catch (e) {
      print(e);
    }

It works fine, and I am able to get the users data. the issue is that when the user close the app and open It again I want to be able to get this data again so I used

await GoogleSignIn().isSignedIn().then((value) {
  if (value) {
    isLogin = true;

    
  GoogleSignIn().currentUser
  GoogleSignIn().currentUser?.id
}

});

when I do that currentUser and currentUser.id both give me null so how can I solve that

Upvotes: 0

Views: 158

Answers (1)

Ahmed Elshazly
Ahmed Elshazly

Reputation: 56

You need to use firebase_auth package along with google signin to store the data in firebase and get it again when launch the app.

final googleSignIn = GoogleSignIn();

  GoogleSignInAccount? _user;

  GoogleSignInAccount get user => _user!;

  Future sigiIn() async {
    final googleUser = await googleSignIn.signIn();
    if (googleUser != null) {
      _user = googleUser;
    }
    final googleAuth = await googleUser!.authentication;
    final credential = GoogleAuthProvider.credential(
        accessToken: googleAuth.accessToken, idToken: googleAuth.idToken);
    return FirebaseAuth.instance.signInWithCredential(credential);
  }

then

call sigiIn() on Button pressed

and you can listen for FirebaseAuth.instance.authStateChanges() through a streamBuilder before the HomeScreen as Following in the main.dart.

home: StreamBuilder(
            stream: FirebaseAuth.instance.authStateChanges(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return Center(
                  child: CircularProgressIndicator(),
                );
              } else if (snapshot.hasData) {
                return MainScreen();
              } else if (snapshot.hasError) {
                return Center(
                  child: Text('Try again later!!!'),
                );
              } else {
                return SignInScreen();
              }
            }),

Upvotes: 1

Related Questions