Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create sharedpreferences class and use it everywhere in my flutter App

Tags:

flutter

How to do it, please give me an idea. It's like a global class which can be accessed by every other class, I actually want to build a util class so that all these things will be only there and I can call these things with just object of util class.

Look this is how I have been doing it

SharedPreferences sharedPreferences;

sharedPreferences = await SharedPreferences.getInstance();
                      sharedPreferences.setString('uwr_name', ctrUwrName.text);
                      getCredential();

And this getCredentail() method I have called where I want data from sharePref.but i don't know Y I need to call it at the time of Setting the data, if I won't put it at the time of setting the data to sharedpref it will give an error

getCredential() async {
  sharedPreferences = await SharedPreferences.getInstance();
}
like image 702
guruprakash gupta Avatar asked Mar 03 '23 03:03

guruprakash gupta


1 Answers

try shared_preferences. Then You can create your util class like this,

class SessionManager {
  final String auth_token = "auth_token";

//set data into shared preferences like this
  Future<void> setAuthToken(String auth_token) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString(this.auth_token, auth_token);
  }

//get value from shared preferences
  Future<String> getAuthToken() async {
    final SharedPreferences pref = await SharedPreferences.getInstance();
    String auth_token;
    auth_token = pref.getString(this.auth_token) ?? null;
    return auth_token;
  }
}

to set value in setAuthToken method do,

 SessionManager prefs =  SessionManager();
 prefs.setAuthToken(welcome.data.auth_token);

to get value from getAuthToken method do,

 Future<String> authToken = prefs.getAuthToken();
 authToken.then((data) {
 print("authToken " + data.toString());
 },onError: (e) {
     print(e);
 });

I have created this gist for your use.

like image 120
Ravinder Kumar Avatar answered Mar 05 '23 18:03

Ravinder Kumar