How to use shared preferences to keep user logged in flutter?

2 Min Read

Shared Preferences is a key-value store that is used to persist data in a Flutter application between app launches. To use Shared Preferences in Flutter, you need to use the shared_preferences package.

Here’s an example of how you could use Shared Preferences to keep a user logged in:

  1. Add the shared_preferences package to your pubspec.yaml file:
  shared_preferences: ^0.5.12

2. Import the shared_preferences package in your Dart code:

import 'package:shared_preferences/shared_preferences.dart';

3. To store the user’s login state, you could use the setBool method to set a value of true or false in Shared Preferences:

Future<void> setUserLoggedIn(bool value) async {
  final prefs = await SharedPreferences.getInstance();
  prefs.setBool('loggedIn', value);

4. To retrieve the user’s login state, you could use the getBool method to retrieve the value of 'loggedIn' from Shared Preferences:

Future<bool> isUserLoggedIn() async {
  final prefs = await SharedPreferences.getInstance();
  return prefs.getBool('loggedIn') ?? false;

5. Finally, you can use these methods in your Flutter app to keep the user logged in. For example, when the user logs in, you can call the setUserLoggedIn method with a value of true, and when the user logs out, you can call it with a value of false. When your app starts, you can call the isUserLoggedIn method to check if the user is logged in, and if so, redirect them to the appropriate page.

Share this Article
Leave a comment