saveRecentForward static method

void saveRecentForward(
  1. List<RecentForward> recentList
)

保存最近转发的会话 最多保存五条

Implementation

static void saveRecentForward(List<RecentForward> recentList) async {
  final recentForwardKey = '$recentForwardSPKey${IMKitClient.account()}';
  final recentForwardStr =
      await PreferenceUtils.getString(recentForwardKey, '');

  // 以新数据为基础,合并缓存中不重复的条目(新数据优先,通过 contains 去重)
  final mergedList = <RecentForward>[...recentList];
  if (recentForwardStr.isNotEmpty) {
    final cachedList =
        RecentForward.fromJsonArray(jsonDecode(recentForwardStr));
    for (final cached in cachedList) {
      if (!mergedList.contains(cached)) {
        mergedList.add(cached);
      }
    }
  }

  // 按时间从大到小排序,保留最近的 maxRecentForward 条
  mergedList.sort((a, b) => b.time.compareTo(a.time));
  final saveList = mergedList.length > maxRecentForward
      ? mergedList.sublist(0, maxRecentForward)
      : mergedList;

  final jsonArray = RecentForward.toJsonList(saveList);
  await PreferenceUtils.saveString(recentForwardKey, jsonEncode(jsonArray));
}