flutterfirebase-authenticationgoogle-signin

How to check if user is already logged in using Google Sign in and Firebase Auth to retrieve their data?


I have a simple game made in Flutter and I can log in the user but I don't know how to check if the user is logged and how to get user's data if so.

For log in I am using this method, after log in the user I can get his data:

Future<String> signInWithGoogle() async{

    print("INICIALIZANDO LOGIN COM GOOGLE...");

    googleSignInAccount = await googleSignIn.signIn();
    googleSignInAuthentication = await googleSignInAccount.authentication;

    final AuthCredential credential = GoogleAuthProvider.getCredential(
        accessToken: googleSignInAuthentication.accessToken,
        idToken: googleSignInAuthentication.idToken,

    );

    AuthResult authResult = await _auth.signInWithCredential(credential);

    user = authResult.user;

    assert(!user.isAnonymous);
    assert(await user.getIdToken() != null);

    currentUser = await _auth.currentUser();
    assert(user.uid == currentUser.uid);

    uid = user.uid;
    name = user.displayName;
    email = user.email;
    imageUrl = user.photoUrl;

    print(uid);
    print(email);
    print(name);
    print(imageUrl);

    return 'signInWithGoogle succeded: $user';

  }

And for signOut this:

  void signOutGoogle() async{

    print("DESLOGOU!");
  await googleSignIn.signOut();

  }

Solution

  • MyAppClient.dart

    Future getCurrentUser() async {
    FirebaseUser _user = await FirebaseAuth.instance.currentUser();
    print("User: ${_user.displayName ?? "None"}");
    return _user;}
    

    Main.dart

    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: GSTheme.backgroundColor,
      ),
      debugShowCheckedModeBanner: false,
      home: MyAppClient().getCurrentUser() != null
          ? HomeViewController()
          : LoginViewController(),
    );