从 flutter 中监听 firestore 数据库中的两个 collections

Listen to two collections in firestore database from flutter

我一直在尝试听两个不同的 collection 文档。一个如下所示。它基本上将 real-time 数据写入屏幕。我也想听另一个 collection 但执行一个特定的功能。请问我该怎么办? 非常感谢任何帮助!!

Expanded(
                      child: StreamBuilder(
                        stream:
                        FirebaseFirestore.instance.collection('location').snapshots(),
                        builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
                          if (!snapshot.hasData) {
                            return Center(child: CircularProgressIndicator());
                          }
                          return ListView.builder(
                              itemCount: snapshot.data?.docs.length,
                              itemBuilder: (context, index) {
                                return ListTile(
                                  title:
                                  Text(snapshot.data!.docs[index]['name'].toString()),
                                  subtitle: Row(
                                    children: [
                                      Text(snapshot.data!.docs[index]['latitude']
                                          .toString()),
                                      SizedBox(
                                        width: 20,
                                      ),
                                      Text(snapshot.data!.docs[index]['longitude']
                                          .toString()),
                                    ],
                                  ),
                                  trailing: IconButton(
                                    icon: Icon(Icons.directions),
                                    onPressed: () {
                                      Navigator.of(context).push(MaterialPageRoute(
                                          builder: (context) =>
                                              MyMap(snapshot.data!.docs[index].id)));
                                    },
                                  ),
                                );
                              });
                        },
                      )),

您可以收听其他 firebase 集合并像这样调用您的函数。

FirebaseFirestore.instance
    .collection('location')
    .snapshots()
    .listen((QuerySnapshot querySnapshot) {

  final  firestoreList = querySnapshot.docs;
  print(firestoreList.first.data());

}).onError((e) => print(e));