How can I cache Firebase real-time database data in Flutter to avoid showing loading screen on every page?

huangapple go评论68阅读模式
英文:

How can I cache Firebase real-time database data in Flutter to avoid showing loading screen on every page?

问题

我是新手学习Flutter,当我从Firebase实时数据库获取数据时,我正在使用FutureBuilder。
每次我导航/访问使用FutureBuilder的页面时,它在获取数据时显示加载屏幕。

现在我的问题是,我不想破坏用户的体验,每次他们导航到包含FutureBuilder的页面时都显示加载屏幕。

我正在考虑在哪里以及如何放置我的缓存并存储一个名为“isFetched”的布尔变量。
但我仍然不知道如何做。我应该使用状态管理,还是有其他解决方案可以解决这个问题?提前谢谢!

英文:

I am new to Flutter and I'm using FutureBuilder when I fetch data in firebase real-time database.
Evey time I navigate/visit a page that use FutureBuilder, it shows a loading screen while it's fetching the data.

Now my problem is I don't want to ruin my user's experience to show a loading screen everytime they navigate to a page that contain FutureBuilder.

I'm trying to think on how and where should I put my cache and store a boolean variable named "isFetched".
But I still don't know on how to do it. Should I use a State Management or is there any solution that could fix this problem? Thank you in advance!

答案1

得分: 2

为了最好地解决您描述的问题,我建议重构您的代码,使用IndexedStack来进行页面导航。

其工作方式是,所有页面小部件仅构建一次并保存在内存中(在小部件树中),但每次只有一个在顶部可见。当您导航到另一页时,它不会重新构建页面小部件,而只是将该小部件交换到前台页面,因此没有重新加载,也没有延迟。

有助于完成此操作的参考资料:

英文:

To best solve the problem you describe,
I would suggest refactoring your code to use the IndexedStack for your page navigation.

The way this works is that all of the page widgets are built once and kept in memory (in the widget tree), but only one is on top and visible at a time.
When you navigate to another page it is not rebuilding the page widget, but simply swapping that widget to be the front page - so there is no reload, and no delay.

References that will help you to do this :

答案2

得分: 0

Firebase Cloud Firestore为您完成了所有这些。如果您无法使用它,其他解决方案会变得更加复杂,因为同步信息可能会非常棘手。

想象一下用户有两台设备,都在保存相同的数据,服务器应该保留哪个版本?最新创建的数据,还是服务器先收到的数据?

SQLite适用于结构化数据,但您可以将数据保存为JSON字符串,然后使用系统首选项将该JSON推送到服务器,如果可以这样做,那将会简单得多。

再次强调,这并不是一个简单的答案,会因项目而异。

英文:

Firebase Cloud Firestore makes all of this for you. If You can't use this, other solution is much more complicated as syncing information can be very tricky.

Imagine the user has 2 devices, both saving the same data, which version should the server keep, the newest created data, or the data the server received first?

SQLite is good for structured data, but you could save your data as a JSON string using System Preferences and just push that JSON to the server, it's a lot simpler if can do it this way.

Again, this really not a simple answer to give and varies from project to project.

huangapple
  • 本文由 发表于 2023年5月30日 12:54:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76361710.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定