Skip to content

Instantly share code, notes, and snippets.

@bharathraj-e
Last active February 4, 2023 09:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bharathraj-e/3a835f75a944f930fda308a01703cce7 to your computer and use it in GitHub Desktop.
Save bharathraj-e/3a835f75a944f930fda308a01703cce7 to your computer and use it in GitHub Desktop.
flutter shared preferences singleton shortcut for set and get
import 'package:shared_preferences/shared_preferences.dart';
class Prefs {
static SharedPreferences _prefs;
// call this method from iniState() function of mainApp().
static Future<SharedPreferences> init() async {
_prefs = await SharedPreferences.getInstance();
return _prefs;
}
//sets
static Future<bool> setBool(String key, bool value) async =>
await _prefs.setBool(key, value);
static Future<bool> setDouble(String key, double value) async =>
await _prefs.setDouble(key, value);
static Future<bool> setInt(String key, int value) async =>
await _prefs.setInt(key, value);
static Future<bool> setString(String key, String value) async =>
await _prefs.setString(key, value);
static Future<bool> setStringList(String key, List<String> value) async =>
await _prefs.setStringList(key, value);
//gets
static bool getBool(String key) => _prefs.getBool(key);
static double getDouble(String key) => _prefs.getDouble(key);
static int getInt(String key) => _prefs.getInt(key);
static String getString(String key) => _prefs.getString(key);
static List<String> getStringList(String key) => _prefs.getStringList(key);
//deletes..
static Future<bool> remove(String key) async => await _prefs.remove(key);
static Future<bool> clear() async => await _prefs.clear();
}
@bharathraj-e
Copy link
Author

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Prefs.init(); // initialize here ! important
  runApp(MyApp());
}

@Bashirkhalil
Copy link

Good we can use get it also .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment