Home > database >  Listen to two collections in firestore database from flutter
Listen to two collections in firestore database from flutter

Time:04-23

I have been trying to listen to two different collection documents. One is shown below. It basically writes the real-time data to the screen. I want to listen to the other collection as well but execute a particular function instead. How should I proceed, please? Truly appreciate any help!!

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

CodePudding user response:

You can listen to other firebase collections and call your functions like this.

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

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

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