Issue
Always required object of SharedPreferences
but we access using await
Like.
await SharedPreferences.getInstance();
That's why I thought create Singleton class of SharedPreferences
and create static method for GET & SET data in SharedPreferences.
But I dont know how to do this, I try but cant get success
Please Help me
Solution
For handle singleton class SharedPreference
follow there 3 steps
-
1. Put this class in your project
import 'dart:async' show Future;
import 'package:shared_preferences/shared_preferences.dart';
class PreferenceUtils {
static Future<SharedPreferences> get _instance async => _prefsInstance ??= await SharedPreferences.getInstance();
static SharedPreferences _prefsInstance;
// call this method from iniState() function of mainApp().
static Future<SharedPreferences> init() async {
_prefsInstance = await _instance;
return _prefsInstance;
}
static String getString(String key, [String defValue]) {
return _prefsInstance.getString(key) ?? defValue ?? "";
}
static Future<bool> setString(String key, String value) async {
var prefs = await _instance;
return prefs?.setString(key, value) ?? Future.value(false);
}
}
2. Initialize this class from your initState() of main class
PreferenceUtils.init();
3. Access your methods like
PreferenceUtils.setString(AppConstants.USER_NAME, "");
String username = PreferenceUtils.getString(AppConstants.USER_NAME);
Answered By - Sanjayrajsinh
Answer Checked By - Senaida (JavaFixing Volunteer)