Flutter: Keep firebase user logged in forever until manual log out

45 Views Asked by At

I use firebase authentication in my flutter app. When I test it in the android emulator, the user is logged out once I re-deploy the app over the IDE. On a real device the user gets logged out after a few hours. How can I prevent that? I saw that some people store the user credentials (e-mail & password) in the shared preferences, but this seems not to be the way to go, especially regarding security. This is my code:

class AuthenticationService {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  Stream<User?> get authStateChanges => _auth.authStateChanges();

  Future<AuthResult> signIn(String email, String password) async {
    try {
      if (_auth.currentUser == null) {
        final userCredential = await _auth.signInWithEmailAndPassword(
            email: email, password: password);
        print('User is signed in');
        return AuthResult(success: true, message: 'User is signed in');
      } else {
        print('User is already signed in');
        return AuthResult(success: true, message: 'User is already signed in');
      }
    } on FirebaseAuthException catch (e) {
      print('User is not signed in $e');
      return AuthResult(success: false, message: mapErrorCodeToMessage(e.code));
    }
  }
}

main

   // Use StreamBuilder to listen for auth changes. If auth is null, show sign-in widget.
   @override
      Widget build(BuildContext context) {
        return StreamBuilder<User?>(
          stream: authService.authStateChanges,
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const CircularProgressIndicator();
            } else if (snapshot.hasData && snapshot.data != null) {
              return ThemeBuilder(
                authService: authService,
                themeModeNotifier: themeModeNotifier,
                child: MyHomePage(
                  title: 'My Homepage',
                  firestore: Firestore(snapshot.data!.uid),
                  authService: authService,
                  themeModeNotifier: themeModeNotifier,
                ),
              );
            } else {
              return MaterialAppProvider(home: SignInPage(authService: authService), themeMode: themeModeNotifier.value,);
            }
          },
        );
      }
...
0

There are 0 best solutions below