如何在颤振中创建 SharedPreferences 的 Singleton 类 [英] How to create Singleton class of SharedPreferences in flutter

查看:21
本文介绍了如何在颤振中创建 SharedPreferences 的 Singleton 类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SharedPreferences 始终是必需的对象,但我们使用 await Like 访问.

Always required object of SharedPreferences but we access using await Like.

等待 SharedPreferences.getInstance();

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

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

推荐答案

处理单例类 SharedPreference 有 3 个步骤-

For handle singleton class SharedPreference follow there 3 steps -

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);

这篇关于如何在颤振中创建 SharedPreferences 的 Singleton 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆