如何在 Flutter 中更新来自 Firestore 的数据?

How to update data from Firestore in Flutter?

我想在 FirebaseFirestore 实例中使用更新方法,但它不起作用。 我已将 id 初始化为字符串,即有状态小部件中的字符串 Id

这是包含按钮小部件的 ViewData 页面

class ViewData extends StatefulWidget {
  const ViewData({Key? key, required this.document, required this.id})
      : super(key: key);

  final Map<String, dynamic> document;
  final String id;
Widget button() {
    return InkWell(
      onTap: () {
        FirebaseFirestore.instance.collection("mytask").doc(widget.id).update({
          "title": titleController.text,
          "description": descriptionController.text,
          "type": type,
          "category": category,
          "format": format,
        });
        Navigator.pop(context);
      },
      child: Container(
        height: 56,
        width: MediaQuery.of(context).size.width,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(15),
        ),
        child: const Center(
          child: Text(
            "Update",
            style: TextStyle(
              color: Colors.white,
              fontSize: 18,
              fontWeight: FontWeight.w600,
            ),
          ),
        ),
      ),
    );
  }

还有一个名为主页的页面已写入快照。

 return ListView.builder(
                  itemCount: snapshot.data.docs.length,
                  itemBuilder: (context, index) {
                    Map<String, dynamic> document = snapshot.data.docs[index]
                        .data() as Map<String, dynamic>;
                    return InkWell(
                      onTap: () {
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (builder) =>
                                    ViewData(
                                      document: document,
                                      id : snapshot.data.docs[index].id,
                                    ),
                            ),
                        );
                      },

帮我找到正确的文档id。

如果要更改文档中的许多数据,请使用set()方法,set如果不存在则创建新文档或覆盖文档中的新数据

        FirebaseFirestore.instance.collection("mytask").doc(widget.id).set({
          "title": titleController.text,
          "description": descriptionController.text,
          "type": type,
          "category": category,
          "format": format,
        });

查看更多how to add data to cloud firestore

您需要添加“SetOptions(merge: true)”,如下所示。

  Future<void> setData({
    required String path,
    required Map<String, dynamic> data,
  }) async {
    final reference = FirebaseFirestore.instance.doc(path);
    return reference
        .set(data, SetOptions(merge: true))
        .timeout(const Duration(seconds: timeOutSecond))
        .catchError((onError) {
      if (onError is SocketException) {
        throw Failure(
          exception: onError,
          message: "No internet connection",
          code: onError.message,
        );
      } else if (onError is TimeoutException) {
        throw Failure(
          exception: onError,
          message: "Timeout...",
          code: onError.message,
        );
      } else {
        throw Failure(
          exception: onError,
          message: "An undefined Error happened.",
        );
      }
    });
  }

能否使用快照类型尝试下面的代码

builder: (BuildContext context,
                            AsyncSnapshot<QuerySnapshot> snapshot) {
                          if (snapshot.hasData &&
                              snapshot.data.docs.length != 0) {
                            List<DocumentSnapshot> snap =
                                snapshot.data.docs;
    return ListView.builder(
                  itemCount: snapshot.data.docs.length,
                  itemBuilder: (context, index) {
                    Map<String, dynamic> document = snapshot.data.docs[index]
                        .data() as Map<String, dynamic>;
                    return InkWell(
                      onTap: () {
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (builder) =>
                                    ViewData(
                                      document: document,
                                      id : snap[index].id,
                                    ),
                            ),
                        );
                      },
    }