简体   繁体   English

如何从 Firestore 获取文档 ID 列表

[英]How do I get a list of document ID’s from Firestore

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.我需要一个集合中的文档 ID 列表,所以我可以在 DropdownButton 中使用它,它将 select 特定文档。

The code below prints out the doc.id for each document in the collection.下面的代码打印出集合中每个文档的 doc.id。

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.我需要列表中每个文档的 doc.id。

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

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()注意* 使用 async/await 时,您必须使用不带.then()await关键字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM