那么,在Flutter中缓存最简单的方法是什么呢



该应用程序是一个简单的新闻阅读器,它显示WordPress的帖子,没有什么花哨的,不使用BLOC,继承的Widget,Firebase。我希望它显示缓存的数据(这是最新的10篇帖子(,即使用户离线。

因此,如果用户离线显示缓存数据;或者以某种方式默认数据是缓存数据。

从WP REST API获取第一个Post[Id]如果缓存的Json文件包含Post[id],则显示缓存的数据;Else getPosts((;并显示装载指示器。还请更新本地JSON文件。

获取JSON数据的代码:

// Function to fetch list of posts
Future<String> getPosts() async {
var res = await http
.get(Uri.encodeFull(apiUrl + "posts?_embed&per_page=10"), //TODO make it unlimited
headers: {"Accept": "application/json"});
setState(() {
var resBody = json.decode(res.body);
posts = resBody;
});
return "Success!";
}

未来得到的帖子和显示加载指标:

body: FutureBuilder<List<String>>(
future: getPosts(),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? ListViewPosts(posts: snapshot.data)
: Center(child: CircularProgressIndicator());
},
),

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

这可能会帮助你。它使用ScopedModel,但它也可以很容易地成为一个简单的类,尽管如果您希望模型触发UI刷新,则必须删除notifyListeners()调用或用自己的机制替换它。

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()。这将从内存(即从_allRecords(获取记录,或者触发刷新,从而进行HTTP调用并更新记录。缓存的数据在30分钟后自动过期,如果您想强制刷新(例如,如果用户明确点击刷新按钮(,可以传递forceRefresh: true

在体验了许多缓存解决方案后,以下是我所学到的按复杂性排序的内容:

1-使用共享首选项2-使用配置单元数据库3-使用消防商店离线服务4-使用sqflite

另一种缓存方式是使用hive a No-SQL数据库,它检索文档更快,而且易于使用。当用户上网时,只需刷新蜂窝中的数据

有关更多详细信息,请查看:https://github.com/shashiben/Anime-details了解如何使用蜂窝进行缓存

相关内容

最新更新