flu*_*ter 2 dart firebase flutter google-cloud-firestore
我一定是误解了hasDataa的方法QuerySnaphot。在我的StreamBuilder我想返回一个widget通知用户collection查询中没有项目。我已经删除了 Firestore 中的集合,所以那里肯定没有数据。但是当我运行以下代码时:
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(),
);
}
}
},
),
Run Code Online (Sandbox Code Playgroud)
我想要做的就是返回一个小部件,通知用户快照是否为空。例如Text('You have no messages')
这里的问题是当查询没有返回文档时snapshots()也会返回 a QuerySnapshot。因此,您可以像这样扩展您的条件:
if (!snapshot.hasData || snapshot.data.documents.isEmpty) {
return Text('You have no messages.');
} else {
...
}
Run Code Online (Sandbox Code Playgroud)
虽然,实际上你不应该返回You have no messageswhen snapshot.dataisnull因为它是null在查询完成之前。因此,我会做这样的事情:
if (!snapshot.hasData) {
return Text('Loading...');
}
if (snapshot.data.documents.isEmpty) {
return Text('You have no messages.');
}
return ListView(..);
Run Code Online (Sandbox Code Playgroud)
这忽略了错误处理,但是,也可以添加。
请注意,这snapshot.hasData是使用 确定连接状态的替代方法snapshot.connectionState。
| 归档时间: |
|
| 查看次数: |
2345 次 |
| 最近记录: |