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).
To build a communication bridge between your Flutter app and Auth0, you need to set up a callback URL to receive the authentication result in your application after a user logs in with Auth0. A callback URL is a mechanism by which an authorization server communicates back to your application.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With