Home > Net >  how to keep user logged in
how to keep user logged in

Time:07-15

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';
}

CodePudding user response:

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.

CodePudding user response:

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).

  • Related