簡體   English   中英

如何獲取flutter中Firestore文檔的個數

[英]How to get the number of Firestore documents in flutter

我正在構建一個 flutter 應用程序並使用 Cloud Firestore。 我想獲取數據庫中所有文檔的數量。

我試過了

Firestore.instance.collection('products').toString().length

但它沒有用。

它應該是 - Firestore.instance.collection('products').snapshots().length.toString();

Firebase 沒有正式提供任何函數來檢索集合中的文檔數量,相反,您可以獲取集合的所有文檔並獲取它的長度。

有兩種方式:

1)

final int documents = await Firestore.instance.collection('products').snapshots().length;

這將返回一個 int 值。 但是,如果您不使用 await,它會返回一個 Future。

2)

final QuerySnapshot qSnap = await Firestore.instance.collection('products').getDocuments();
final int documents = qSnap.documents.length;

這將返回一個 int 值。

但是,這兩種方法都會獲取集合中的所有文檔並對其進行計數。

謝謝

Future<int> getCount() async {
    int count = await FirebaseFirestore.instance
        .collection('collection')
        .get()
        .then((value) => value.size);
    return count;
  }

在 Cloud Firebase 2.0 中,有一種計算集合中文檔的新方法。 根據參考說明,計數不計為每個文檔的讀取,而是元數據請求:

“[AggregateQuery] 表示特定位置的數據,用於在不檢索實際文檔的情況下檢索元數據。”

例子:

final CollectionReference<Map<String, dynamic>> productList = FirebaseFirestore.instance.collection('products');

      Future<int> countProducts() async {
        AggregateQuerySnapshot query = await productList.count().get();
        debugPrint('The number of products: ${query.count}');
        return query.count;
      }

首先,您必須從該集合中獲取所有文檔,然后您可以通過文檔列表獲取所有文檔的長度。 下面應該可以完成工作。

Firestore.instance.collection('products').getDocuments.then((myDocuments){
 print("${myDocuments.documents.length}");
});
 Future getCount({String id}) async => Firestore.instance
      .collection(collection) //your collectionref
      .where('deleted', isEqualTo: false)
      .getDocuments()
      .then((value) {
    var count = 0;
    count = value.documents.length;

    return count;
  });

這是飛鏢語言...

由於您正在等待未來,因此必須將其放置在異步函數中

QuerySnapshot productCollection = await 
Firestore.instance.collection('products').get();
int productCount = productCollection.size();

集合中的文檔數量

我們可以使用 Firebase 聚合查詢,而不是使用 get() 或 snapshots() 獲取所有文檔並對它們進行計數。 這將為您提供計數。

這是一個適用於 Flutter 的示例:

final collection = FirebaseFirestore.instance.collection("products");
final query = collection.where("status", isEqualTo: "active");
final countQuery = query.count();
final AggregateQuerySnapshot snapshot = await countQuery.get();
debugPrint("Count: ${snapshot.count}");

您可以在此處找到更多詳細信息: https://firebase.google.com/docs/firestore/query-data/aggregation-queries

最簡單的方法:

int count = await FirebaseFirestore.instance.collection('Collection_Name').get().then((value) => value.size);
print(count);

您想要從 firebase 中獲取數據,因此該調用將返回一個 Future。 為了獲得 int 值,您必須使用 StreamBuilder 小部件或 FutureBuilder。

例如:

Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
    stream: FirebaseFirestore.instance.collection("<collection name>").getStream().snapshot(),
    builder: (context, snapshot) {
      return Scaffold(
          backgroundColor: Colors.white,
          body: SafeArea(
              child: Stack(children: [
            Text(
                  "${snapshot.data!.docs.length}"
            )
          ]));
    });

}

Firestore.instance
    .collection("products")
    .get()
    .then((QuerySnapshot querySnapshot) {
  print(querySnapshot.docs.length);
});

@2022使用最新版本的 FirebaseFirestore,您現在無需檢索整個集合即可獲得計數。

CollectionReference ref = FirebaseFirestore.instance.collection('collection');

int count = (await ref.count().get()).count;

以上建議將導致客戶端下載集合中的所有文檔以獲取計數。 作為一種解決方法,如果您的寫入操作不經常發生,您可以將文檔的長度放入 firebase 遠程配置,並在您從 Firestore 集合中添加/刪除文檔時更改它。 然后,您可以在需要時從 firebase 遠程配置中獲取長度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM