我正在处理一个有多个用户的应用程序。我有一个资源列表,这个资源列表就像一个巧克力列表(只有一个且唯一)。现在,我在所有活动用户的主屏幕上显示此巧克力。现在,用户可以单击巧克力并将其提供给他们。但是,当发生这种情况时,我想刷新所有已登录的用户,以确保没有两个用户使用相同的巧克力。
我正在使用数据库触发器来监视数据库中的更改。我能够做到这一点,但我关心的是如何刷新listView。
我的算法如下:
1)监视数据库中的更改。 2)获取新的数据集。 3)更新视图
我尝试如下创建syncDatabaseFunction:
Future syncDatabaseFunction() async {
CollectionReference reference = Firestore.instance.collection('Chocolates');
reference.snapshots().listen((querySnapshot){
querySnapshot.documentChanges.forEach((change){
print("Changed Chocolate");
BackendOperations.getAllChocolates().then((value){
var chocolateTemp = (value as List<ChocolateModel>)
.where((element) => (element.chocolateColor == "Brown"))
.toList();
print("Count is ");
return chocolateTemp;
});
});
});
}
对于列表视图,我正在使用futureBuilder。
答案 0 :(得分:1)
我认为,如果您使用StreamBuilder
,则可以解决问题。
用户删除或添加新评论时,它会向所有用户显示。
StreamBuilder
是这样做的,是Stream的观察者。
这是我的代码:
Widget getListComment() {
return StreamBuilder<QuerySnapshot>(
stream: Firestore.instance
.collection('comments')
.where('post', isEqualTo: postRef)
.orderBy('createdAt', descending: true)
.snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Column(
children: <Widget>[
CircularProgressIndicator(),
],
);
default:
return new ListView(
children:
snapshot.data.documents.map((DocumentSnapshot document) {
return CommentItem(
key: Key(document.documentID),
comment: Comment.fromDoc(document),
myUser: widget.myUser,
);
}).toList(),
);
}
},
);
}
我收到了Firebase的评论,并显示在ListView
中,我认为这就像您的巧克力。