Skip to content

Instantly share code, notes, and snippets.

@shaon2016
Created July 18, 2021 09:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shaon2016/b22f6155ccfadc0ed0664afd340c971f to your computer and use it in GitHub Desktop.
Save shaon2016/b22f6155ccfadc0ed0664afd340c971f to your computer and use it in GitHub Desktop.
A Singleton sharedpref using GetX
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
class SharedPref extends GetxService {
static late SharedPreferences _pref;
Future<SharedPref> init() async {
_pref = await SharedPreferences.getInstance();
return this;
}
static Future setString(String key, String value) async {
await _pref.setString(key, value);
}
static Future setInt(String key, int value) async {
await _pref.setInt(key, value);
}
static Future setBool(String key, bool value) async {
await _pref.setBool(key, value);
}
static Future setDouble(String key, double value) async {
await _pref.setDouble(key, value);
}
static Future setStringList(String key, List<String> value) async {
await _pref.setStringList(key, value);
}
static getString(String key) {
_pref.getString(key);
}
static getInt(String key) {
_pref.getInt(key);
}
static getBool(String key) {
_pref.getBool(key);
}
static getDouble(String key) {
_pref.getDouble(key);
}
static getStringList(String key) {
_pref.getStringList(key);
}
}
# From your main.dart file
void main() {
initServices();
runApp(MyApp());
}
initServices() async {
await Get.putAsync(() => SharedPref().init());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment