我想使用快照检查Firestore中的文档是否存在,在尝试获取不存在的文档时出现红色屏幕错误,返回null。
StreamBuilder(
stream: Firestore.instance
.collection('Resumes')
.document(uid)
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
};
如何检查名称为uid的文档是否存在?
答案 0 :(得分:1)
执行以下操作来代替document('uid'):
Firestore.instance .collection('Resumes').documents;
然后,您可以遍历文档,以检查是否与documentId属性匹配。
final document = snapshot.data.firstWhere((doc) => doc.documentId = uid, orElse: () => null)
然后,检查文档!= null
答案 1 :(得分:1)
您可以在文档快照上使用exists方法来检查文档是否存在:
DocumentSnapshot docSnapshot = await Firestore.instance.collection('Resumes').document(uid).get();
bool isDocExists = docSnapshot.exists(); //true if exists and false otherwise
答案 2 :(得分:1)
snapshot.hasData
也会返回 true
。
要检查文档是否存在,可以检查是否snapshot.data.data==null
因此,您必须将代码更改为:
StreamBuilder(
stream: Firestore.instance
.collection('Resumes')
.document(uid)
.snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData) {
if(snapshot.data.data==null){
//document does not exist
}
else{
//document exists
}
} else{
//Waiting for data
return Center(child: CircularProgressIndicator());
}
};
答案 3 :(得分:0)
var res=Firestore.instance .collection('Resumes').documents;
if(res==null){
print("no documents found");
}else{
//there are documents
}
将集合实例设置为变量,并使用if语句检查变量是否为null。