Created
January 17, 2019 03:03
-
-
Save faisalraja/9b628439978c67b2fb6515cf202a3992 to your computer and use it in GitHub Desktop.
SharedPreference helper for flutter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Preference { | |
static SharedPreferences _prefs; | |
static Map<String, dynamic> _memoryPrefs = Map<String, dynamic>(); | |
static Future<SharedPreferences> load() async { | |
if (_prefs == null) { | |
_prefs = await SharedPreferences.getInstance(); | |
} | |
return _prefs; | |
} | |
static void setString(String key, String value) { | |
_prefs.setString(key, value); | |
_memoryPrefs[key] = value; | |
} | |
static void setInt(String key, int value) { | |
_prefs.setInt(key, value); | |
_memoryPrefs[key] = value; | |
} | |
static void setDouble(String key, double value) { | |
_prefs.setDouble(key, value); | |
_memoryPrefs[key] = value; | |
} | |
static void setBool(String key, bool value) { | |
_prefs.setBool(key, value); | |
_memoryPrefs[key] = value; | |
} | |
static String getString(String key, {String def}) { | |
String val; | |
if (_memoryPrefs.containsKey(key)) { | |
val = _memoryPrefs[key]; | |
} | |
if (val == null) { | |
val = _prefs.getString(key); | |
} | |
if (val == null) { | |
val = def; | |
} | |
_memoryPrefs[key] = val; | |
return val; | |
} | |
static int getInt(String key, {int def}) { | |
int val; | |
if (_memoryPrefs.containsKey(key)) { | |
val = _memoryPrefs[key]; | |
} | |
if (val == null) { | |
val = _prefs.getInt(key); | |
} | |
if (val == null) { | |
val = def; | |
} | |
_memoryPrefs[key] = val; | |
return val; | |
} | |
static double getDouble(String key, {double def}) { | |
double val; | |
if (_memoryPrefs.containsKey(key)) { | |
val = _memoryPrefs[key]; | |
} | |
if (val == null) { | |
val = _prefs.getDouble(key); | |
} | |
if (val == null) { | |
val = def; | |
} | |
_memoryPrefs[key] = val; | |
return val; | |
} | |
static bool getBool(String key, {bool def = false}) { | |
bool val; | |
if (_memoryPrefs.containsKey(key)) { | |
val = _memoryPrefs[key]; | |
} | |
if (val == null) { | |
val = _prefs.getBool(key); | |
} | |
if (val == null) { | |
val = def; | |
} | |
_memoryPrefs[key] = val; | |
return val; | |
} | |
} |
class Preferences {
// ...
static void setStringList(String key, List<String> value) {
_prefs.setStringList(key, value);
_memoryPrefs[key] = value;
}
static void remove(String key) {
_prefs.remove(key);
_memoryPrefs.remove(key);
}
static List<String>? getStringList(String key) => _memoryPrefs[key] ?? _prefs.getStringList(key);
// ...
}
I added the above methods
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@keehyun2 It's much better now, I added this to load function