flutter - 遍历 Firestore 集合中的所有文档,并将这些文档添加到 Flutter 中的另一个集合中
问题描述
我正在尝试遍历 Firestore 集合中的所有文档及其字段,并通过单击我的颤振应用程序中的按钮将它们添加到另一个集合中。
到目前为止,我有这个函数可以读取集合中的所有文档并将它们打印到控制台没有问题:
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()
fromprint(result.data())
然后在我的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
,你不能删除它,因为函数不知道要操作什么。
我想你可以对documentsLoopFromFirestore
功能上的一切,试试这个。
void documentsLoopFromFirestore() {
FirebaseFirestore.instance.collection('myCollection').get().then(
(value) {
value.docs.forEach(
(result) {
FirebaseFirestore.instance.collection('myOtherCollection222').add(
result.data(),
);
},
);
},
);
}
推荐阅读
- python - 通过列中的标签列表对熊猫数据框行进行分组的有效方法
- reactjs - 如何在 ReactJs 中更改状态时添加段落
- java - 如何从 Java 1.8.0 升级到 Java 11?
- api - 将组添加到 Auth Code Flow pt 的范围。1
- python - 用文本小部件编写的行间距
- python - 如何在 pandas pd.read_excel 中通过其索引而不是其名称来指定列 dtype
- angular - 将 Keycloak 与 Angular 集成
- json - 如何在ansible中将字典或列表转换为字符串
- github - 如何让dependabot仅触发安全更新
- javascript - 为可以将文件夹归档为 ZIP 以供下载的 ftp 文件服务器创建 Web UI