【问题标题】:How to update collection documents in firebase in flutter?如何在flutter中更新firebase中的集合文档?
【发布时间】:2020-03-19 21:23:30
【问题描述】:

我想更新一个文档字段,我尝试了以下代码,但它没有更新。

谁能给我一个解决方案,好吗?

我的代码:

var snapshots = _firestore
        .collection('profile')
        .document(currentUserID)
        .collection('posts')
        .snapshots();

    await snapshots.forEach((snapshot) async {
      List<DocumentSnapshot> documents = snapshot.documents;

      for (var document in documents) {
        await document.data.update(
          'writer',
          (name) {
            name = this.name;
            return name;
          },
        );
        print(document.data['writer']);
       //it prints the updated data here but when i look to firebase database 
       //nothing updates !
      }
    });

【问题讨论】:

  • 试试document.setData(Map);而不是document.data.update

标签: firebase flutter dart google-cloud-firestore


【解决方案1】:

对于此类情况,我始终建议遵循documentation 中的确切类型,以查看可用的选项。例如,DocumentSnapshot objectdata 属性是Map&lt;String, dynamic&gt;。当您为此调用 update() 时,您只是在更新文档的内存中表示,而不是实际更新数据库中的数据。

要更新数据库中的文档,您需要调用DocumentReference.updateData method。要从DocumentSnapshotDocumentReference,请调用DocumentSnapshot.reference property

比如:

document.reference.updateData(<String, dynamic>{
    name: this.name
});

与此无关,您的代码看起来有点不习惯。我建议使用getDocuments 而不是snapshots(),因为后者可能会导致无限循环。

var snapshots = _firestore
        .collection('profile')
        .document(currentUserID)
        .collection('posts')
        .getDocuments();

await snapshots.forEach((document) async {
  document.reference.updateData(<String, dynamic>{
    name: this.name
  });
})

这里的区别在于getDocuments() 读取数据一次,然后返回,而snapshots() 将开始观察文档,并在发生更改时将它们传递给我们(包括当您更新名称时)。

【讨论】:

  • 执行此操作后,它返回“预期 2 个位置参数,但找到了 1 个。尝试添加缺少的参数。”并且这个“参数类型'Future Function(动态)'不能分配给参数类型'Iterable '。”在以下行forEach ((document) async {。你知道会发生什么吗?
【解决方案2】:

2021 年更新:

API 中很多东西都发生了变化,例如,FirestoreFirebaseFirestore 替换,doc 在里面等等。

  • 更新文档

    var collection = FirebaseFirestore.instance.collection('collection');
    collection 
        .doc('some_id') // <-- Doc ID where data should be updated.
        .update({'key' : 'value'}) // <-- Updated data
        .then((_) => print('Updated'))
        .catchError((error) => print('Update failed: $error'));
    
  • 更新文档中的嵌套值:

    var collection = FirebaseFirestore.instance.collection('collection');
    collection 
        .doc('some_id') // <-- Doc ID where data should be updated.
        .update({'key.foo.bar' : 'nested_value'}) // <-- Nested value
        .then((_) => print('Updated'))
        .catchError((error) => print('Update failed: $error'));
    

【讨论】:

    猜你喜欢
    • 2019-02-13
    • 2020-08-28
    • 2020-05-24
    • 2023-02-10
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    相关资源
    最近更新 更多