【问题标题】:Does Firestore perform a read every time a page is built?每次构建页面时,Firestore 都会执行读取吗?
【发布时间】:2021-05-11 11:41:32
【问题描述】:

我正在使用 Flutter 设计一个应用,并使用 Firestore 作为我的数据库。

我有这个页面,它基本上从 Firestore 中的特定集合中获取所有内容并为用户列出。

我还不太熟悉 Firestore 方面的工作原理,并希望尽可能对其进行优化,以避免不必要的数据库读取。在这种情况下我的问题是:每次用户打开此屏幕时,Firestore 会在此集合中执行读取吗?还是仅当此集合中的某些内容发生更改时?

假设用户打开了这个列表,然后转到他的个人资料,然后又回到了这个列表。如果同时集合没有任何变化,那么数据库中会有 1 次还是 2 次读取?

我需要使用 Stream 来实现吗?

这个列表在 Flutter 中的实现

FutureBuilder<List<Store>>(
  future: DatabaseService().storeList,
  builder: (context, snapshot) {
    if (!snapshot.hasData) {
      return Loading();
    } else {
      return ListView.builder(
        scrollDirection: Axis.vertical,
        shrinkWrap: true,
        itemBuilder: (context, index) => StoreTile(store: snapshot.data[index]),
        itemCount: snapshot.data.length,
      );
    }
  },
);

数据库东西的实现

class DatabaseService {

  // Collection reference
  final CollectionReference storeCollection = FirebaseFirestore.instance.collection('stores');

  // Make a store list from snapshot object
  List<Store> storeListfromSnapshot(QuerySnapshot snapshot) {
    return snapshot.docs.map((doc){
      return Store(
        name:         doc.data()['name']  ?? '',
        description:  doc.data()['description']  ?? '',
        image:        doc.data()['image'] ?? ''
      );
    }).toList();
  }

  // Get instantaneous stores list
  Future<List<Store>> get storeList async {
    return storeListfromSnapshot(await storeCollection.get());
  }

}

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    每个get() 调用都会从服务器获取数据。所以在这里,因为您在集合上使用get(),假设您有 5 个文档,那么它将读取 5 个文档。如果您再次进入该页面,那么它也会计算 5 次文档读取。

    如果要从缓存中获取数据,则使用snapshots(),它会从缓存中返回数据,如果有任何修改,则会从服务器返回数据。

    您也可以在get()方法中添加参数GetOptions,例如:

    get(GetOptions(source : Source.cache))
    

    这将始终从缓存中获取数据,完全忽略服务器。


    您还可以在此处监视阅读的文档:

    https://firebase.google.com/docs/firestore/monitor-usage

    另请注意,如果您保持 firebase 控制台打开,那么您将获得意外读取。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多