| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- import 'package:flutter/foundation.dart';
- /// 简单内存缓存,用于基础资料分页接口。
- /// TTL 内相同 cacheKey 的请求直接返回缓存结果。
- class ApiCache {
- final int ttlSeconds;
- final String? _keyPrefix;
- final Map<String, _CacheEntry> _store = {};
- ApiCache({this.ttlSeconds = 120, String? keyPrefix}) : _keyPrefix = keyPrefix;
- String _fullKey(String key) =>
- _keyPrefix != null ? '${_keyPrefix}_$key' : key;
- /// 缓存命中返回已有数据;未命中调用 [fetcher] 并存入缓存。
- /// [skipCache] 为 true 时跳过缓存直接调用 [fetcher]。
- Future<List<T>> getOrFetch<T>(
- String key,
- Future<List<T>> Function() fetcher, {
- bool skipCache = false,
- }) async {
- final fullKey = _fullKey(key);
- if (!skipCache) {
- final entry = _store[fullKey];
- if (entry != null && !entry.isExpired) {
- if (kDebugMode) debugPrint('[ApiCache] HIT $fullKey');
- return entry.data as List<T>;
- }
- }
- if (kDebugMode) debugPrint('[ApiCache] MISS $fullKey');
- final data = await fetcher();
- _store[fullKey] = _CacheEntry(
- data,
- DateTime.now().add(Duration(seconds: ttlSeconds)),
- );
- return data;
- }
- /// 移除指定 key 的缓存条目。
- void invalidate(String key) => _store.remove(_fullKey(key));
- /// 清除所有缓存(下拉刷新时调用)。
- void clear() => _store.clear();
- }
- class _CacheEntry {
- final dynamic data;
- final DateTime expiresAt;
- _CacheEntry(this.data, this.expiresAt);
- bool get isExpired => DateTime.now().isAfter(expiresAt);
- }
|