如何从文档快照中获取Firestore文档ID?

8
QuerySnapshot querySnapshot = await _collectionRef   
                                  .limit(1)
                                  .orderBy('date')                                                                    
                                  .getDocuments();
var list = querySnapshot.documents;

querySnapshot.documents.map((document) { 
    print('Document : $document'); // not printing anything.
  });

if(list.length > 0) {
   print('ID : ${list[0].documentID}'); // not working
}

这是我尝试的确切代码… 代码有哪些错误?

5个回答

6
product.id

documentID已经不推荐使用,应该使用.id代替。 请用新的方法替换被弃用的成员。


5

如果它没有做你期望的事情,那它会做什么? - Doug Stevenson
你的代码是有效的!但我尝试了不同的方法。我会更新代码。请告诉我哪里出了问题。 - agriz
如果你有一个不同于你之前提出的问题,你应该发布另一个帖子,而不是编辑你现有的帖子。 - Doug Stevenson
抱歉,问题还是一样的。只是我删除了一个存储querySnapshot的变量。现在我已经更新了,这是我现在拥有的代码。 - agriz
我必须使用 forEach 而不是 map。不确定为什么列表变量没有打印任何内容。我正在使用完整路径 querySnapshot.documents[0].documentID。感谢您的帮助.. - agriz

1
对于DocumentSnapshot, document.id

1
这与已经在此处提供的答案有何不同? - camille
1
不是 .documentId 而是 .id - Muhammad Bilal
已经发布过了,包括之前属性被弃用的提及。 - camille

0
对于DocumentSnapshot,document.documentID

0

此外,在字符串插值时,请使用反引号。

print('ID : ${list[0].documentID}'); // not working
print(`ID : ${list[0].documentID}`); // working

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接