Files
social-app/docs/bugs/sharedpreferences缺少统一管理模型.md
T

86 lines
2.3 KiB
Markdown

# SharedPreferences 缺少统一管理模型
## 问题描述
当前 `SharedPreferences` 的使用散落各处,缺乏统一的数据模型约束:
### 现状
1. **Key 散落**
- `reminder_notification_callbacks.dart` 中定义:`'calendar_reminder_pending_notification_responses_v1'`
- 各处直接使用字符串 key,容易拼写错误或冲突
2. **重复获取实例**
```dart
final prefs = await SharedPreferences.getInstance(); // 每次都重新获取
```
3. **序列化逻辑分散**
- `ReminderNotificationCallbacks` 自己处理 JSON 序列化/反序列化
- 其他模块可能重复相同逻辑
4. **注册但未统一封装**
- `injection.dart` 只注册了 `SharedPreferences` 实例
- 没有封装成可复用的数据访问层
## 影响
- 维护困难:Key 散落,修改时需要全局搜索
- 容易出错:拼写错误难以发现
- 代码重复:序列化逻辑可能在多处重复实现
- 可测试性差:直接依赖 `SharedPreferences.getInstance()`
## 建议方案
### 1. 创建 `AppPreferences` 数据模型
```dart
class AppPreferences {
static const String _pendingNotificationsKey =
'calendar_reminder_pending_notification_responses_v1';
final SharedPreferences _prefs;
AppPreferences(this._prefs);
List<NotificationResponse> get pendingNotifications {
final list = _prefs.getStringList(_pendingNotificationsKey) ?? [];
return list.map(_decode).toList();
}
Future<void> setPendingNotifications(List<NotificationResponse> value) {
return _prefs.setStringList(_pendingNotificationsKey, value.map(_encode).toList());
}
// 其他偏好设置...
}
```
### 2. 在 injection.dart 中注册
```dart
final sharedPreferences = await SharedPreferences.getInstance();
sl.registerSingleton<AppPreferences>(AppPreferences(sharedPreferences));
```
### 3. 使用方通过接口访问
```dart
// 之前
final prefs = await SharedPreferences.getInstance();
await prefs.setStringList(key, value);
// 之后
sl<AppPreferences>().setPendingNotifications(value);
```
## 涉及文件
- `apps/lib/app/di/injection.dart` - 注册逻辑
- `apps/lib/features/notification/data/services/reminder_notification_callbacks.dart` - 主要使用方
- `apps/lib/features/notification/data/services/ios_notification_payload_bridge.dart` - 另一使用方
## 状态
- [ ] 待修复