skip to Main Content

I want to have a list contains the IDs of the documents in a collection enter image description herefor using the id as string in comparison with something else but I couldn’t find the way to do that

I wrote the following

final firebaseid = FirebaseFirestore.instance.collection('Guests').get().then((value) {
  var id = value;
  print(id);
});

but I couldn’t get the documents ids

3

Answers


  1. Try this

    CollectionReference _collectionRef =
    FirebaseFirestore.instance.collection('collection');
    
    Future<void> getData() async {
        QuerySnapshot querySnapshot = await _collectionRef.get();
    
        final allData = querySnapshot.docs.map((doc) => doc.data()).toList();
    }
    
    Login or Signup to reply.
  2. While Murat’s answer will get you the data of all documents, you seem to be asking for the document IDs. In that case, you’ll want:

    FirebaseFirestore.instance.collection('Guests').get().then((querySnapshot) {
      for (var doc in querySnapshot.docs) {
        var id = doc.id;
        print(id);
      }
    });
    

    The big difference here is that the code handles the fact that the result of calling get on a CollectionReference is a QuerySnapshot, and you’ll need to loop over its docs to get each individual document. This is also shown in the Firebase documentation on getting all documents in a collection.

    Login or Signup to reply.
  3. You can get a list of all ids in a collection like this:

      void getAllGuestsIds() async {
        final docIds = await FirebaseFirestore.instance.collection('Guests').get().then(
              (value) => value.docs.map((e) => e.id).toList(),
            );
        //return or do something else with docIds
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search