简体   繁体   中英

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

I'm trying to loop through all the documents and their fields in a Firestore collection and add them to another collection with the click of a button in my flutter app.

So far I have this function that reads through all the documents in the collection and prints them to the console no problem:

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

Using a button to call documentsLoopFromFirestore() :

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

I successfully get all the data from my Firestore documents printed in the console:

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

Now, I have tried removing the print() from print(result.data()) and then calling these 2 things on my onPressed: () {} button but they both fail:

- First one

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

- Error:

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

- Second one

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

- Error:

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

I know there's some "obvious" thing I should be applying to result.data() but I'm just completely out of ideas.

Can anyone see what am I missing?

first of all idkWhatGoesHereButICantRemoveIt is the name you give the value that returns, usualy i call it value , you cant remove it because the function would not know what to operate on.

I think you can to everything on the documentsLoopFromFirestore function, try this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM