微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在带有Firestore数据库的Flutter列表视图构建器中获取实时更新?

如何解决如何在带有Firestore数据库的Flutter列表视图构建器中获取实时更新?

我正在使用以下代码在listview.builder中构建列表。我已经实现了分页(此处不包括更详细的代码)。

这是查询

Query query = Firestore.instance.collection("users").limit(20);

QuerySnapshot以获取文档

QuerySnapshot _querySnapshot = await query.getDocuments();

QuerySnaphot与DocumentSnapshot的List类型变量相邻。

List<DocumentSnapshot> _notifications = _querySnapshot.documents;

在ListView.Builder中检索到的元素

String name = _notifications[index].data['name'];
int number_of_items = _notifications[index].data['number_of_items'];

现在上面的代码number_of_items中的,但不是实时地被检索,我的意思是如果列表的项目在屏幕上可见,并且具有int值,例如24,可见,但是当后端中的相同值更新为25,而不是在屏幕上同时更新。

我知道我们在波动中使用StreamBuilder时会使用stream:query.snapshots()并检索我们使用的列表项的字段值

int number_of_items = snapshot.data.documents[index]['number_of_items'];

在使用此类功能时,只要在Firestore的后端中更改了值,我们就会获得实时更新

请指导我如何改进代码

QuerySnapshot _querySnapshot = await query.getDocuments();
List<DocumentSnapshot> _notifications = _querySnapshot.documents;

在使用Firestore数据库Flutter应用程序中获取实时更新并维护分页

可以使用吗?

query.snapshots(includeMetadataChanges: true);

如果是,请告诉我如何将其与List<DocumentSnapshot> _notifications

关联

解决方法

您可以创建一个返回Stream<QuerySnapshot>的方法,然后在StreamBuilder中使用该方法:

Stream<QuerySnapshot> getRealTimeData() async* {
  Query query = Firestore.instance.collection("users").limit(20);
  yield* query.snapshots(includeMetadataChanges: true);
}

StreamBuilder(
    stream: getRealTimeData(),builder: (context,AsyncSnapshot<QuerySnapshot> snapshot) {
      if (snapshot.connectionState == ConnectionState.done) {
        return ListView.builder(
            shrinkWrap: true,itemCount: snapshot.data.documents.length,itemBuilder: (BuildContext context,int index) {
              return ListTile(
                contentPadding: EdgeInsets.all(8.0),title:
                    Text(snapshot.data.documents[index].data["name"]),leading: Image.network(
                    snapshot.data.documents[index].data["url"],fit: BoxFit.fill),);
            });
      } else if (snapshot.connectionState == ConnectionState.none) {
        return Text("No data");
      }
      return CircularProgressIndicator();
    },),

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。