我一定误会了hasData
的{{1}}方法。在我的QuerySnaphot
中,我想返回一个StreamBuilder
来通知用户在查询的widget
中没有项目。我已在Firestore中删除了该集合,因此那里肯定没有数据。但是,当我运行以下代码时:
collection
我要做的就是返回一个小部件,通知用户快照是否为空。例如StreamBuilder<QuerySnapshot>(
stream: Firestore.instance
.collection('Events')
.where("bandId", isEqualTo: identifier)
.snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
print('code here is being executed 1');// This gets executed
return Text('helllllp');
} else {
print('Code here is being executed2'); //And this gets executed
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return new Text('Loading...');
default:
return new ListView(
children:
snapshot.data.documents.map((DocumentSnapshot document) {
return CustomCard(
event: document['event'],
location: document['location'],
service: document['service'],
date: document['date'].toDate(),
);
}).toList(),
);
}
}
},
),
答案 0 :(得分:2)
这里的问题是,当查询不返回任何文档时,snapshots()
也将返回QuerySnapshot
。因此,您可以像这样扩展条件:
if (!snapshot.hasData || snapshot.data.documents.isEmpty) {
return Text('You have no messages.');
} else {
...
}
尽管,实际上,当You have no messages
为snapshot.data
时,您不应返回null
,因为在完成查询之前它是null
。因此,我会选择这样的东西:
if (!snapshot.hasData) {
return Text('Loading...');
}
if (snapshot.data.documents.isEmpty) {
return Text('You have no messages.');
}
return ListView(..);
这会忽略错误处理,但是也可以添加错误处理。
通知,snapshot.hasData
是使用snapshot.connectionState
确定连接状态的替代方法。