Flutter - Storing Authenticated User details

2,210

Start Simple

A simple starting point to store the data, which i assume is the form of key/value pairs, would be using shared preferences.

What are Shared Preferences

The main use of Shared Preferences is to save user preferences, settings, maybe data (if not too large) so that next time the application is launched, these pieces of information could be retrieved and used.

How to use

Set an instance variable of Shared Preferences and store the value with a key identifier. Any time you want to retrieve the value when the app starts, just get it using the key. See example below of setting and getting a stored username.

Future<bool> setUserName(String value) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setString("username",value);
}

Future<String> getUserName(String value) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString("username");
}

Installation To installed shared preferences, add this to your package's pubspec.yaml file:

dependencies:
  shared_preferences: ^0.5.7+3

More information on the package page.

Share:
2,210
mortred95
Author by

mortred95

Updated on December 20, 2022

Comments

  • mortred95
    mortred95 over 1 year

    I am new to Flutter and I am writing an app which requires users to login. I already have an API that provides me with a JWT. I then store this using the secure storage library.

    Once the user gets the 200 OK with the token, I want to send another request to the server to retrieve the user's details and store it in a kind of singleton class, so I can use it through out the app until he logs out. There are so many buzzwords being thrown at me right now, Providers and BLoCs.

    I was wondering what is the best practice to store the current logged in user details in the app? Previously I've been aware of storing the data in a singleton class. But now I'm not sure whether I should write a singleton class or a Provider? (I'm still rusty on my knowledge about how Providers and BLoCs work).

  • mortred95
    mortred95 almost 4 years
    Coming over from Android, I am aware of storing user settings in SharedPreferences, however It's a common rule not to store sensitive information in their. Hence why I am using the secure storage library. However, in the context of my question I would still not store the User's data (such as Name, Profile Picture, Email) in SharedPreferences. I am looking for an alternative to this, preferably something like a singleton class.