flutter - 如何在 StreamBuilder 中添加 whereIn
问题描述
我目前遍历列表列表以获取对事件感兴趣的用户。我设置了它,initState
但是在从文档中添加或删除 id 时Firestore
,更改不会反映在 UI 中。我不想手动更新列表。有没有办法将此代码从移动initState
到 a StreamBuilder
?
@override
void initState() {
super.initState();
final interestedUsers = widget.content.interested;
var chunks = [];
for (var i = 0; i < interestedUsers.length; i += 10) {
chunks.add(interestedUsers.sublist(i,
i + 10 > interestedUsers.length ? interestedUsers.length : i + 10));
}
for (var i = 0; i < chunks.length; i++) {
final snapshot = FirebaseFirestore.instance
.collection('users')
.where('uid', whereIn: chunks[i])
.snapshots();
snapshot.forEach((element) {
element.docs.forEach((element) {
final userElement = UserModel.fromFirestore(element);
setState(() {
interested.add(userElement);
});
});
});
}
}
解决方案
你可以像这里这样写......这是一个处理加载和空状态的完整示例:
StreamBuilder(
stream: _firestore
.collection('users')
.where('uid', whereIn: chunks[i])
.snapshots(),
builder:
(BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
//Shows loading indicator
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator( ),
);
}
List<UserNotificationListTile> items = [];
unredNotifications = [];
List<QueryDocumentSnapshot> groups = snapshot.data.docs;
for (QueryDocumentSnapshot g in groups) {
UserNotification userNotification =
new UserNotification.fromSnapshot(g);
items.add(
UserNotificationListTile(
userNotification: userNotification,
),
);
}
//Shows result when there is no data
if (items.length == 0) {
return Center(child: NotificationsEmpty());
}
return Column(
children: [
Expanded(
child: ListView(
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 0),
children: items.reversed.toList(),
),
),
],
);
}),
);
推荐阅读
- payment - php条带支付API
- ionic-framework - 错误类型错误:无法读取未定义的属性“存在”
- python - Django 2.0 - 登录查看测试中的 KeyError
- android - 从另一个活动的堆栈中清除活动
- mongodb - 猫鼬覆盖原始对象而不是更新
- vuetify.js - Vuetify - 组件内部的 CSS 不起作用(生效)
- sql-server - 将查询总和转为排名列
- elasticsearch - logstash 无法从 kafka 正确读取 avro 记录
- tensorflow - Jupyter Notebook 在使用 MaxPool 层时被杀死
- java - 2个线程在java中一次启动