【问题标题】:Loop through all documents in a Firestore collection and add those documents to another collection in Flutter遍历 Firestore 集合中的所有文档,并将这些文档添加到 Flutter 中的另一个集合中
【发布时间】:2021-08-26 13:29:14
【问题描述】:

我正在尝试遍历 Firestore 集合中的所有文档及其字段,并在我的 Flutter 应用程序中单击一个按钮将它们添加到另一个集合中。

到目前为止,我有这个功能可以读取集合中的所有文档并将它们打印到控制台没有问题:

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() 申请一些“显而易见”的东西,但我完全没有想法。

谁能看到我错过了什么?

【问题讨论】:

    标签: flutter dart google-cloud-firestore


    【解决方案1】:

    首先idkWhatGoesHereButICantRemoveIt是你给返回值的名字,通常我称之为value,你不能删除它,因为函数不知道要操作什么。

    我想你可以对documentsLoopFromFirestore函数上的所有东西,试试这个。

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

    【讨论】:

    • BROOOO!!!!你刚刚结束了 3 周的漫长旅程,让这个东西发挥作用!!!!非常感谢你!
    • 乐于助人:)
    猜你喜欢
    • 2020-09-12
    • 2017-04-15
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多