[英]Loop through all firestore documents in a collection AND update them in 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.