簡體   English   中英

如何在flutter更新firebase的收款文件?

[英]How to update collection documents in firebase in flutter?

我想更新文檔字段,我嘗試了以下代碼,但它沒有更新。

任何人都可以給我一個解決方案嗎?

我的代碼:

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 !
      }
    });

對於這種情況,我總是建議遵循文檔中的確切類型,以查看可用的選項。 例如, DocumentSnapshot對象data屬性是Map<String, dynamic> 當您對此調用update()時,您只是在更新文檔的內存表示,而不是實際更新數據庫中的數據。

要更新數據庫中的文檔,您需要調用DocumentReference.updateData方法 並且要從DocumentSnapshotDocumentReference ,您可以調用DocumentSnapshot.reference屬性

所以像:

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()將開始觀察文檔,並在發生更改時(包括更新名稱時)將它們傳遞給我們。

2021 年更新:

API 中發生了很多變化,例如FirestoreFirebaseFirestore取代, doc is in 等。

  • 更新文檔

    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'));

要在不覆蓋整個文檔的情況下更新文檔的某些字段,請使用以下特定於語言的update()方法:

final washingtonRef =  FirebaseFirestore.instance.collection("cites").doc("DC");
washingtonRef.update({"capital": true}).then(
    (value) => print("DocumentSnapshot successfully updated!"),
    onError: (e) => print("Error updating document $e"));

服務器時間戳

您可以將文檔中的字段設置為服務器時間戳,用於跟蹤服務器何時收到更新。

final docRef =  FirebaseFirestore.instance.collection("objects").doc("some-id");
final updates = <String, dynamic>{
  "timestamp": FieldValue.serverTimestamp(),
};

docRef.update(updates).then(
    (value) => print("DocumentSnapshot successfully updated!"),
    onError: (e) => print("Error updating document $e"));

更新嵌套對象中的字段

如果您的文檔包含嵌套對象,您可以在調用 update() 時使用“點符號”來引用文檔中的嵌套字段:

// Assume the document contains:
// {
//   name: "Frank",
//   favorites: { food: "Pizza", color: "Blue", subject: "recess" }
//   age: 12
// }
 FirebaseFirestore.instance
    .collection("users")
    .doc("frank")
    .update({"age": 13, "favorites.color": "Red"});

更新數組中的元素

如果您的文檔包含數組字段,您可以使用 arrayUnion() 和 arrayRemove() 添加和刪除元素。 arrayUnion() 將元素添加到數組,但僅添加不存在的元素。 arrayRemove() 刪除每個給定元素的所有實例。

final washingtonRef =  FirebaseFirestore.instance.collection("cities").doc("DC");

// Atomically add a new region to the "regions" array field.
washingtonRef.update({
  "regions": FieldValue.arrayUnion(["greater_virginia"]),
});

// Atomically remove a region from the "regions" array field.
washingtonRef.update({
  "regions": FieldValue.arrayRemove(["east_coast"]),
});

增加一個數值

您可以增加或減少數字字段值,如以下示例所示。 增量操作將字段的當前值增加或減少給定的數量。

var washingtonRef =  FirebaseFirestore.instance.collection('cities').doc('DC');

// Atomically increment the population of the city by 50.
washingtonRef.update(
  {"population": FieldValue.increment(50)},
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM