即使没有数据更改,Firestore缓存也不起作用 [英] Firestore cache not working even if no data has changed

查看:90
本文介绍了即使没有数据更改,Firestore缓存也不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 Alex Momo的回答,默认情况下,Firestore将文档存储在缓存中并从那里加载,仅包含新文档或更改时,它会再次读取并产生额外费用。

According to Alex Momo's answer, by default, Firestore store documents in cache and load from there, only with new documents or changes it will read again with an additional costs.

print(document.metadata.isFromCache?不是来自网络: FROM NETWORK);

即使我使用FutureBuilder(.getDocuments()),我第一次打开应用程序时也会打印 FROM NETWORK,第二次它再次加载 FROM NETWORK,并且数据库没有更改,因此看起来缓存仅在应用程序真正脱机时才起作用,但是似乎如果有连接,它将始终从服务器加载,有人可以进一步解释吗?

Even if I use FutureBuilder (.getDocuments()), the first time I open the app it prints "FROM NETWORK", on the second time it loads "FROM NETWORK" again, and database had no changes, so looks like the cache only works when the app is really offline, but it seems if there's connection it will load from server always, does anyone can explain more about that?

参数 Source.serverAndCache think是默认设置,并且说明中显示 使Firestore尝试检索最新的(服务器检索的)快照,但是如果无法访问服务器,则退回返回缓存的数据。 ,我认为这意味着:您有联系吗?从服务器加载,如果没有?从缓存加载。但这并没有太大帮助,因为每次我们关闭应用程序并重新打开时,都会再次从服务器加载所有文档。

The parameter Source.serverAndCache I think is the default and the description says "Causes Firestore to try to retrieve an up-to-date (server-retrieved) snapshot, but fall back toreturning cached data if the server can't be reached.", I think it means: you have connection? loading from server, if not? loading from cache. But that does't help much, since every time we close the app and re open it will load all documents from server again.

FutureBuilder(
            future: Firestore.instance.collection("latest").orderBy("date", descending: true)
                .getDocuments(source: Source.serverAndCache ),
            builder: (context, snapshot) {

              if (!snapshot.hasData || snapshot.data.documents.length == null) {
                return Center(
                  child: CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation(Colors.white),
                  ),
                );
              } else if(snapshot.data.documents.length == 0) {

                return Center(
                    child: Padding(
                      padding: const EdgeInsets.only(left: 16, right: 16),
                      child: Text(
                        "Sorry but there's no wallpapers for this character yet!",
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w300,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    )
                );

              } else {

                return GridView.builder(
                    itemCount: snapshot.data.documents.length,
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                      childAspectRatio: screenHeight / screenWidth * 0.4,
                      mainAxisSpacing: 1.0,
                      crossAxisSpacing: 1.0,
                    ),
                    itemBuilder: (context, index) {

                      return _buildGrid(snapshot.data.documents[index], index);

                    }
                );



              }
            }
          )

Widget _buildGrid(DocumentSnapshot document, int index) {

      print(document.metadata.isFromCache ? "NOT FROM NETWORK" : "FROM NETWORK");

      return GestureDetector(
        child: Hero(
          tag: index,
          child: CachedNetworkImage(
            imageUrl: document['url'],
            errorWidget: (context, url, error) => Icon(Icons.error_outline),
            fit: BoxFit.fill,
            filterQuality: FilterQuality.low,

          ),

        ),
        onTap: () {
          Navigator.of(context).push(
              MaterialPageRoute(
                  builder: (context) => DetailScreen(document['url']))
          );
        },
      );
    }


推荐答案

Peter的评论正确。每当您调用 .getDocuments(source:Source.serverAndCache)时,Firestore都需要对照服务器检查数据是否被修改。并且由于这需要服务器读取文档,因此将向您收费。

Peter's comments are correct. Any time you call .getDocuments(source: Source.serverAndCache ), Firestore will need to check against the server to see if the data is modified. And since this requires the server to read the documents, you will be charged for those reads.

如果要强制Firestore从其本地缓存中读取,请使用 .getDocuments(源:Source.Cache)。这意味着您冒着显示陈旧数据的风险,但这是您必须做出的取舍。

If you want to force Firestore to read from its local cache, use .getDocuments(source: Source.Cache). That means you run the risk of showing stale data, but that's a trade-off you'll have to make.

我通常建议使用 onSnapshot 侦听器,因为它们更适合仅将更改从服务器发送到客户端。

I typically recommend using onSnapshot listeners, as they are better suited for sending only the changes from the server to the client.

还可以检出:

  • firestore how to check if new documents added matching a particular query
  • What relationship between firestore snapshotlistener's lifecycle and pricing?

这篇关于即使没有数据更改,Firestore缓存也不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆