如何在抖动中创建SharedPreference的Singleton类

问题描述 投票:2回答:4

总是SharedPreferences的必需对象,但我们使用await Like访问。

await SharedPreferences.getInstance();

这就是为什么我想创建SharedPreferences的Singleton类并为SharedPreferences中的GET&SET数据创建静态方法的原因。

但是我不知道该怎么做,我尝试但无法成功请帮助我

android ios flutter flutter-layout
4个回答
2
投票

这是我的偏好解决方案:

class Storage {
  static const String _some_field = 'some_field';

  static Future<SharedPreferences> get prefs => SharedPreferences.getInstance();

  static Future<String> getSomeStringData() async =>
      (await prefs).getString(_some_field) ?? '';

  static Future setSomeStringData(String phone) async =>
      (await prefs).setString(_some_field, phone);

  static Future clear() async {
    await getSomeStringData(null);
  }
}

1
投票

我将此代码用于单例设置

static Future<SharedPreferences>  getInstance() async
  {
    SharedPreferences preferences ;
    preferences = await SharedPreferences.getInstance();
    return preferences;
  }

然后使用它来还原您的数据,这里我还原userId。

 /// ----------------------------------------------------------
  /// Method that saves/restores the userId
  /// ----------------------------------------------------------
   static Future<String>  getUserId() async {
    return getInstance().then((pref) {
      return pref.get(Constants.userId);
    });
  }

希望有帮助:)


1
投票
class YourClass {
    static final YourClass _singleton = 
           new YourClass._internal();

    factory YourClass(){
            return _singleton;
    }

    YourClass._internal(){
            //initialization your logic here
    }

}

//主代码环境

YourClass mClass = new YourClass(); //将单身人士找回来


0
投票

对于句柄单例类SharedPreference,请遵循以下3个步骤-

1。将此类放在您的项目中

    import 'dart:async' show Future;
    import 'package:shared_preferences/shared_preferences.dart';

    class PreferenceUtils {
      static Future<SharedPreferences> get _instance async => _prefs ??= await SharedPreferences.getInstance();
      static SharedPreferences _prefs;
      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。从您的主类的initState()初始化该类

PreferenceUtils.init();

3。访问您的方法,例如

PreferenceUtils.setString(AppConstants.USER_NAME, "");
String username = PreferenceUtils.getString(AppConstants.USER_NAME);
© www.soinside.com 2019 - 2024. All rights reserved.