shared_preferences缓存

发布时间 2023-12-27 09:22:01作者: 鲤斌

封装

import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';

class JSpUtil {
  JSpUtil._internal(); // 私有的构造方法,防止外部实例化

  factory JSpUtil() => _instance; // 工厂方法,返回 JSpUtil 唯一实例

  static late final JSpUtil _instance = JSpUtil._internal(); // JSpUtil 唯一实例

  static late SharedPreferences _preferences; // SharedPreferences 对象

  static Future<JSpUtil> getInstance() async {
    _preferences = await SharedPreferences.getInstance(); // 获取 SharedPreferences 实例
    return _instance;
  }

  /// 根据key存储int类型
  static Future<bool> setInt(String key, int value) {
    return _preferences.setInt(key, value); // 使用 SharedPreferences 存储 int 类型的数据
  }

  /// 根据key获取int类型
  static int? getInt(String key, {int defaultValue = 0}) {
    return _preferences.getInt(key) ?? defaultValue; // 使用 SharedPreferences 获取 int 类型数据,如果不存在则返回默认值
  }

  /// 根据key存储double类型
  static Future<bool> setDouble(String key, double value) {
    return _preferences.setDouble(key, value); // 使用 SharedPreferences 存储 double 类型的数据
  }

  /// 根据key获取double类型
  static double? getDouble(String key, {double defaultValue = 0.0}) {
    return _preferences.getDouble(key) ?? defaultValue; // 使用 SharedPreferences 获取 double 类型数据,如果不存在则返回默认值
  }

  /// 根据key存储字符串类型
  static Future<bool> setString(String key, String value) {
    return _preferences.setString(key, value); // 使用 SharedPreferences 存储字符串类型的数据
  }

  /// 根据key获取字符串类型
  static String? getString(String key, {String defaultValue = ""}) {
    return _preferences.getString(key) ?? defaultValue; // 使用 SharedPreferences 获取字符串类型数据,如果不存在则返回默认值
  }

  /// 根据key存储布尔类型
  static Future<bool> setBool(String key, bool value) {
    return _preferences.setBool(key, value); // 使用 SharedPreferences 存储布尔类型的数据
  }

  /// 根据key获取布尔类型
  static bool? getBool(String key, {bool defaultValue = false}) {
    return _preferences.getBool(key) ?? defaultValue; // 使用 SharedPreferences 获取布尔类型数据,如果不存在则返回默认值
  }

  /// 根据key存储字符串类型数组
  static Future<bool> setStringList(String key, List<String> value) {
    return _preferences.setStringList(key, value); // 使用 SharedPreferences 存储字符串类型数组
  }

  /// 根据key获取字符串类型数组
  static List<String> getStringList(String key,
      {List<String> defaultValue = const []}) {
    return _preferences.getStringList(key) ?? defaultValue; // 使用 SharedPreferences 获取字符串类型数组,如果不存在则返回默认值
  }

  /// 根据key存储Map类型
  static Future<bool> setMap(String key, Map value) {
    return _preferences.setString(key, json.encode(value)); // 使用 SharedPreferences 存储 Map 类型的数据,将 Map 转为 json 字符串存储
  }

  /// 根据key获取Map类型
  static Map getMap(String key) {
    String jsonStr = _preferences.getString(key) ?? ""; // 使用 SharedPreferences 获取存储的 json 字符串
    return jsonStr.isEmpty ? Map : json.decode(jsonStr); // 将 json 字符串解码为 Map 对象,如果 json 为空则返回空 Map 对象
  }
}