Home > front end >  How do I get a list of document ID’s from Firestore
How do I get a list of document ID’s from Firestore

Time:09-13

I need a list of document ID’s from a collection, so I can use it in a DropdownButton, which will select the specific document.

The code below prints out the doc.id for each document in the collection.

void getDevices () async {
  var firebaseUser = FirebaseAuth.instance.currentUser?.email;
  print('firebaseUser: $firebaseUser');
  await firestoreInstance.collection(devices).where('email', isEqualTo: '$firebaseUser').get().then((value) {
     value.docs.forEach((element) {print(element.id);});
  });

I need the doc.id for each document in a list.

CodePudding user response:

you can do something like:

void getDevices () async {
  var firebaseUser = FirebaseAuth.instance.currentUser?.email;
  print('firebaseUser: $firebaseUser');
 var query = await firestoreInstance.collection(devices).where('email', isEqualTo: ' 
 $firebaseUser').get();
 List documentsIds = query.docs.map((doc)=>doc.id); 
 });

CodePudding user response:

To summarise the solution from the comments:


void getDevices () async {
  var firebaseUser = FirebaseAuth.instance
    .currentUser?.email;
  var snapshot =  await firestoreInstance.collection(devices)
    .where('email', isEqualTo: '$firebaseUser')
    .get();
  var idList = snapshot.docs.map(doc=> doc.id).toList();

// rest of your code here

}

Note* when using async/await, you must use the await keyword without .then()

  • Related