starwork_flutter/lib/common/utils/shared_preferences_utils.dart
2025-09-06 15:42:26 +08:00

84 lines
2.2 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';
class SharedPreferencesUtils {
static SharedPreferences? _prefs;
// 初始化
static Future<void> init() async {
_prefs = await SharedPreferences.getInstance();
}
/// 存储带过期时间的字符串
/// [key] 键
/// [value] 值
/// [expiry] 过期时间(如 Duration(hours: 1)
static Future<bool> setStringWithExpiry(
String key,
String value,
Duration expiry,
) async {
final prefs = _prefs;
if (prefs == null) return false;
final expiryKey = '_expiry_$key'; // 用 _expiry_ 前缀标记过期时间
final expireAt = DateTime.now().add(expiry).millisecondsSinceEpoch;
// 使用 Transaction 确保原子性(可选)
return await prefs.setString(key, value) &&
await prefs.setInt(expiryKey, expireAt);
}
/// 获取带过期时间的字符串
/// 如果已过期,则自动删除并返回 null
static String? getStringWithExpiry(String key) {
final prefs = _prefs;
if (prefs == null) return null;
final expiryKey = '_expiry_$key';
final expireAt = prefs.getInt(expiryKey);
// 如果没有过期时间,视为永不过期(或已过期?根据需求)
if (expireAt == null) {
return prefs.getString(key);
}
// 比较当前时间
final now = DateTime.now().millisecondsSinceEpoch;
if (now > expireAt) {
// 已过期,清理
removeKeyWithExpiry(key);
return null;
}
return prefs.getString(key);
}
/// 删除带过期时间的键(清理 value 和 expiry
static Future<void> removeKeyWithExpiry(String key) async {
final prefs = _prefs;
if (prefs == null) return;
final expiryKey = '_expiry_$key';
await prefs.remove(key);
await prefs.remove(expiryKey);
}
static Future<bool> setString(String key, String value) async {
return _prefs?.setString(key, value) ?? Future.value(false);
}
static String? getString(String key) {
return _prefs?.getString(key);
}
// bool
static Future<void> setBool(String key, dynamic value) async {
_prefs?.setBool(key, value);
}
static Future<bool?> getBool(String key) async {
return _prefs?.getBool(key);
}
}