栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

那么在Flutter中进行缓存的最简单方法是什么?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

那么在Flutter中进行缓存的最简单方法是什么?

一个简单的基于时间的缓存不需要太多代码。

这可能会帮助您。它使用

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/410193.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号