skip to Main Content

this is how I login using Google and firebase. but I couldn’t figure it out as to how to keep the use logged in.. when the app restarts it log the user out automatically

import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';

final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = GoogleSignIn();

Future<String> signInWithGoogle() async {
  final GoogleSignInAccount? googleSignInAccount = await googleSignIn.signIn();
  final GoogleSignInAuthentication googleSignInAuthentication =
      await googleSignInAccount!.authentication;
  final AuthCredential credential = GoogleAuthProvider.credential(
    accessToken: googleSignInAuthentication.accessToken,
    idToken: googleSignInAuthentication.idToken,
  );
  final authResult = await _auth.signInWithCredential(credential);
  final User? user = authResult.user;
  assert(!user!.isAnonymous);
  final User? currentUser =  _auth.currentUser;
  assert(user!.uid == currentUser!.uid);
  return 'signInWithGoogle succeeded: $user';
}

3

Answers


  1. Chosen as BEST ANSWER

    It may not be the best way to do it but this worked.

    chooseLogin() {
      if (_auth.currentUser == null) {
        return const SignUo();
      } else {
        return const Splash();
      }
    }
    
    

  2. You can call await _auth.currentUser() at the start of your app to check the current user. Further you may want to store the token in shared preferences.

    Login or Signup to reply.
  3. Firebase automatically persists the user credentials in the shared storage, and restores them when the app restarts. There’s nothing you need to do for that.

    What you will need to do though is listen for the authentication state as shown in the first code snippet in the documentation on getting the current user:

    FirebaseAuth.instance
      .authStateChanges()
      .listen((User? user) {
        if (user != null) {
          print(user.uid);
        }
      });
    

    This code needs to run when the app starts, so I typically have it in my top-level widget and then store the user in the state so that my build method can use it. By listening to auth state changes, the code is run automatically when the user sign-in state is restored at startup (which happens asynchronously, so may take a few moments) but also when the user would later be logged out (for example, if you disable the account in the Firebase Authentication console).

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