androidflutterdartsharedpreferencessingle-instance

How to create a single instance of shared preferences which can be used in full project in flutter


Whenever we have to use shared preferences we have to create an instance of it.

In flutter creating an instance of shared preference is asynchronous;

final prefs = await SharedPreferences.getInstance();

we have to create its instance always whenever we have to use it like above.

Is there a way to create a single instance of shared preferences which will be available to the overall project and we don't have to create its instance again and again in Flutter?


Solution

  • To create Singleton class of SharedPreference:

    Put this class in 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);
             }
           }
    
    Initialize this class in initState() main class
     void main() async {
      // Required for async calls in `main`
      WidgetsFlutterBinding.ensureInitialized();
    
      // Initialize PreferenceUtils instance.
      await PreferenceUtils.init();
    
      runApp(MyApp());
    }
    
    Access in methods
    PreferenceUtils.setString(AppConstants.USER_ID, "");
    String userId = PreferenceUtils.getString(AppConstants.USER_ID);
    

    more: https://dev.to/lucianojung/flutter-singelton-pattern-1a38