Flutter 封装shared_preferences 为同步方法

涉及到的插件

dependencies:
  synchronized: ^3.0.0+2
  shared_preferences: ^2.0.7

不多说直接上代码

import 'package:shared_preferences/shared_preferences.dart';
import 'package:synchronized/synchronized.dart';

class SpHelper{
  static SpHelper? _instance;
  static late SharedPreferences prefs;
  static final Lock _lock = Lock();

  static Future<SpHelper?> init() async {
    if (_instance == null) {
      print("SpHelper初始化中");
      await _lock.synchronized(() async {
          // 保持本地实例直到完全初始化。
          var singleton = SpHelper();
          await singleton._init();
          _instance = singleton;
      });
    }
    print("SpHelper初始化完成");
    return _instance;
  }


  Future _init() async {
    prefs = await SharedPreferences.getInstance();
  }

  static putStorage(String key, value) async {
    if (value is String) {
      prefs.setString(key, value);
    } else if (value is num) {
      prefs.setInt(key, value as int);
    } else if (value is double) {
      prefs.setDouble(key, value);
    } else if (value is bool) {
      prefs.setBool(key, value);
    } else if (value is List) {
      prefs.setStringList(key, value.cast<String>());
    }
  }

  // 获取
  static getStorage(String key, [dynamic replace]) {
    if (prefs == null) return;
    return prefs.get(key) ?? replace;
  }

  // 移除
  static removeStorage(String key)  {
    if (prefs == null) return;
    prefs.remove(key);
  }

  static removeAllStorage() {
    if (prefs == null) return;
    prefs.clear();
  }

}

使用之前需要先初始化,尽量在全局main里

  void main() {
    Global.init().then((e) {
      runApp(const MyApp());
      //必须在APP启动后初始化不然获取不到sp对象
         await SpHelper.init();

    });

使用方法:

SpHelper.getStorage("字段名", "默认值");

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值