使用 Fultter (Dart) 仅更新 FireStore 中的一个字段

Dan*_*ira 5 dart flutter google-cloud-firestore

我的 FireStore 中保存了一份数据,我只需要更新一个字段。

name: "Daniel",
lastname: "Pereira",
age: 25,
isLogged: false
Run Code Online (Sandbox Code Playgroud)

例如,我只需将isLogged更新为true 。

Dan*_*ira 6

仅传递给 updateDate 一个 json,例如:{"isLogged": true }

final CollectionReference collectionReference = Firestore.instance.collection("profiles");
collectionReference.document("profile")
                .updateData({"isLogged": true})
                .whenComplete(() async {
              print("Completed");
            }).catchError((e) => print(e));
Run Code Online (Sandbox Code Playgroud)

如果您使用交易,您可以这样做:

Firestore.instance.runTransaction((transaction) async {
          await transaction.update(
              collectionReference.document("profile"), {"isLogged": true});
        };
Run Code Online (Sandbox Code Playgroud)

希望这对某人有帮助!;)

  • Firebase 不允许更新单个字段,它会更新整个文档。不过,您可以将其设置为仅更新 1 个字段(但仍需为整个文档更新付费)。确保使用“Reference.set({}, SetOptions(merge: true))”仅更新 1 个字段并保留其他字段。 (3认同)