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();
}
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.
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