簡體   English   中英

遍歷 Firestore 集合中的所有文檔,並將這些文檔添加到 Flutter 中的另一個集合中

[英]Loop through all documents in a Firestore collection and add those documents to another collection in Flutter

我正在嘗試遍歷 Firestore 集合中的所有文檔及其字段,並通過單擊我的 flutter 應用程序中的按鈕將它們添加到另一個集合中。

到目前為止,我有這個 function 讀取集合中的所有文檔並將它們打印到控制台沒有問題:

documentsLoopFromFirestore() {
     FirebaseFirestore.instance
      .collection('myCollection')
      .get()
      .then((idkWhatGoesHereButICantRemoveIt) {
        idkWhatGoesHereButICantRemoveIt.docs.forEach((result) {
      print(result.data());
    });
  });
}

使用按鈕調用documentsLoopFromFirestore()

_button(){
  return ElevatedButton(
    onPressed: () {
      documentsLoopFromFirestore();
    }, 
    child: Text('press me'));
}

我成功地從控制台中打印的 Firestore 文檔中獲取了所有數據:

I/flutter (23876): {lastName: smith, name: peter}
I/flutter (23876): {lastName: doe, name: john}

現在,我嘗試從print(result.data())中刪除print() ),然后在我的onPressed: () {}按鈕上調用這兩個東西,但它們都失敗了:

- 第一

onPressed: () {
  FirebaseFirestore.instance.collection('myOtherCollection222').add(documentsLoopFromFirestore());
}

- 錯誤:

E/flutter (23876): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Null check operator used on a null value

- 第二個

onPressed: () {
  documentsLoopFromFirestore().forEach((doc) => {
          FirebaseFirestore.instance.collection('myOtherCollection69').add(doc)});
}

- 錯誤:

════════ Exception caught by gesture ═══════════════════════════════════════════
The method 'forEach' was called on null.
Receiver: null
Tried calling: forEach(Closure: (dynamic) => Set<Future<DocumentReference<Map<String, dynamic>>>>)
════════════════════════════════════════════════════════════════════════════════

我知道我應該將一些“明顯”的東西應用於result.data()但我完全沒有想法。

誰能看到我錯過了什么?

首先idkWhatGoesHereButICantRemoveIt是你給返回值的名稱,通常我稱之為value ,你不能刪除它,因為 function 不知道要操作什么。

我想你可以到documentsLoopFromFirestore LoopFromFirestore function 上的所有內容,試試這個。

  void documentsLoopFromFirestore() {
    FirebaseFirestore.instance.collection('myCollection').get().then(
      (value) {
        value.docs.forEach(
          (result) {
            FirebaseFirestore.instance.collection('myOtherCollection222').add(
                  result.data(),
                );
          },
        );
      },
    );
  }

暫無
暫無

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

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