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?