user9622529
user9622529

Reputation:

How to keep user logged in in Flutter?

I have a flutter app. I want to keep users logged in even after exiting the app. I have main.dart file, login.dart and dashboard.dart. i want main.dart to redirect to login.dart if the user has not signed in but directly to dashboard if shared preference value is found.

Upvotes: 4

Views: 15100

Answers (3)

Amaan
Amaan

Reputation: 66

You can even use a shared preference plugin from pub.dev, check this plugin. I had used it too, if you need more explanation, pls ask me I'll help. first, when the user is logging in, create a sharted preferences instance. then store the user id value there.

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('uid', userCredential.user!.uid);

then after that to check whether the user logged in or not, check that instance.

SharedPreferences prefs = await SharedPreferences.getInstance();
bool userStatus = prefs.containsKey('uid');

'userStatus' will return true, if a user is already logged in. then you can display all details about the user using the 'uid'. when the user is signing out, remove the 'uid' from the sharedpreference.

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.remove('uid');

Upvotes: 3

Doug Stevenson
Doug Stevenson

Reputation: 317392

You don't have to do anything to keep the user signed in with Firebase Authentication. The SDK will remember the user and sign them in again when the app is restarted. It doesn't help to store anything in shared preferences. According to the documentation:

The Firebase SDKs for all platforms provide out of the box support for ensuring that your user's authentication state is persisted across app restarts or page reloads.

When you should do instead is use a state listener stream to find out when the SDK has verified that the user object is available when the user is signed in. Be sure to read the documentation about that as well.

FirebaseAuth.instance
  .authStateChanges()
  .listen((User user) {
    if (user == null) {
      print('User is currently signed out!');
    } else {
      print('User is signed in!');
    }
  });

Upvotes: 13

Salim Murshed
Salim Murshed

Reputation: 1441

You can use Share Preference to stay log in and log out. You can check how-to-use-shared-preferences-to-keep-user-logged-in-flutter.

Upvotes: 0

Related Questions