首页 > 解决方案 > Flutter,FireStore如何一次更新所有文档中的字段

问题描述

我正在制作某种笔记应用程序,我想实现一个可以触发所有文档中的字段的功能。例如,所有文档都会有一个字段“isDone”,当用户按下全部清除按钮时,所有文档中的字段“isDone”都会变为 true。

我正在使用 Stream Builder 和 Staggered Gridview 来显示来自火存储的所有数据,并且我想将逻辑将所有这些数据转换为 void 方法。

这是我简化的代码:

class Notes extends StatefulWidget {
  @override
  _NotesState createState() => _NotesState();
}

class _NotesState extends State<Notes> {
  var collection = FirebaseFirestore.instance.collection('notes');

  void makeAllDocsDone() {
    // logic here
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.clear),
        onPressed: () {
          makeAllDocsDone();
        },
      ),
      body: StreamBuilder(
        stream: FirebaseFirestore.instance.collection('notes').snapshots(),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (!snapshot.hasData) return const SizedBox.shrink();
          return Container(
            padding: EdgeInsets.symmetric(horizontal: 10),
            child: StaggeredGridView.countBuilder(
              crossAxisCount: 30,
              mainAxisSpacing: 10,
              crossAxisSpacing: 10,
              itemCount: snapshot.data!.docs.length,
              itemBuilder: (context, index) {
                return InkWell(
                  child: Container(
                    color: Colors.red,
                    child: Column(
                      children: [
                        Text(snapshot.data!.docs[index]['title']),
                        TextButton(
                          child: Text('DONE'),
                          onPressed: () {
                            // This only change selected docs
                            snapshot.data!.docs[index].reference.update({
                              'isDone': 'true',
                            });
                          },
                        ),
                      ],
                    ),
                  ),
                );
              },
              staggeredTileBuilder: (index) {
                return StaggeredTile.count(15, 15);
              },
            ),
          );
        },
      ),
    );
  }
}


标签: firebasefluttergoogle-cloud-firestore

解决方案


推荐阅读