首页 > 解决方案 > 如何在颤振中创建 SharedPreferences 的 Singleton 类

问题描述

总是需要的对象,SharedPreferences但我们使用 awaitLike 访问。

await SharedPreferences.getInstance();

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

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

标签: androidiosflutterflutter-layout

解决方案


对于处理单例​​类,请SharedPreference遵循 3 个步骤 -

1.把这个类放到你的项目中

    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. 从你的主类的 initState() 初始化这个类

PreferenceUtils.init();

3.访问您的方法,例如

PreferenceUtils.setString(AppConstants.USER_NAME, "");
String username = PreferenceUtils.getString(AppConstants.USER_NAME);

推荐阅读