一个简单的基于时间的缓存不需要太多代码。
这可能会帮助您。它使用
ScopedModel,但它可能很容易成为一个简单的类,尽管
notifyListeners()如果您希望模型触发UI刷新,则必须删除调用或将其替换为自己的机制。
class MyModel extends Model{ Duration _cachevalidDuration; DateTime _lastFetchTime; List<MyRecord> _allRecords; MyModel(){ _cachevalidDuration = Duration(minutes: 30); _lastFetchTime = DateTime.fromMillisecondsSinceEpoch(0); _allRecords = []; } /// Refreshes all records from the API, replacing the ones that are in the cache. /// Notifies listeners if notifyListeners is true. Future<void> refreshAllRecords(bool notifyListeners) async{ _allRecords = await MyApi.getAllRecords(); // This makes the actual HTTP request _lastFetchTime = DateTime.now(); if( notifyListeners ) this.notifyListeners(); } /// If the cache time has expired, or forceRefresh is true, records are refreshed from the API before being returned. /// Otherwise the cached records are returned. Future<List<MyRecord>> getAllRecords({bool forceRefresh = false}) async{ bool shouldRefreshFromApi = (null == _allRecords || _allRecords.isEmpty || null == _lastFetchTime || _lastFetchTime.isBefore(DateTime.now().subtract(_cachevalidDuration)) || forceRefresh); if( shouldRefreshFromApi )await refreshAllRecords(false); return _allRecords; }}要从中获取数据
MyModel,UI只需调用
getAllRecords()。这将从内存中获取记录(即from
_allRecords),或者触发刷新以进行HTTP调用并更新记录。缓存的数据将在30分钟后自动过期,并且如果您要强制刷新(例如,如果用户明确点击刷新按钮),则可以通过
forceRefresh:true。



