How to create Singleton class of SharedPreferences in flutter

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

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published