【发布时间】:2020-06-10 10:52:14
【问题描述】:
在我作为注册过程的一部分构建的应用程序中,为每个“用户”文档创建了一个子集合,其中包含多达 100 个文档。
我正在尝试在StreamBuilder 中显示这些子集合文档。
我有一个无法解决的奇怪错误。 StreamBuilder 在用户第一次查看时不显示数据。相反,它返回一个空列表。
我可以看到文档已在子集合中正确生成。数据正在使用 StreamBuilder 的页面之前的页面上设置。即使有延迟,我也会认为新文档会刚刚开始出现在 StreamBuilder 中。
Firebase console view
StreamBuilder确实在应用重新启动或用户注销并再次登录时按预期显示数据。
下面是我正在使用的代码:
Stream<QuerySnapshot> provideActivityStream() {
return Firestore.instance
.collection("users")
.document(widget.userId)
.collection('activities')
.orderBy('startDate', descending: true)
.snapshots();
}
...
Widget activityStream() {
return Container(
padding: const EdgeInsets.all(20.0),
child: StreamBuilder<QuerySnapshot>(
stream: provideActivityStream(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
if(snapshot.data == null) {
return CircularProgressIndicator();
}
if(snapshot.data.documents.length < 1) {
return new Text(
snapshot.data.documents.toString()
);
}
if (snapshot != null) {
print('$currentUser.userId');
}
if (
snapshot.hasData && snapshot.data.documents.length > 0
) {
print("I have documents");
return new ListView(
children: snapshot.data.documents.map((
DocumentSnapshot document) {
return new PointCard(
title: document['title'],
type: document['type'],
);
}).toList(),
);
}
}
)
);
}
编辑:根据评论请求添加主构建
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
title: Text("Home"),
actions: <Widget>[
],
bottom: TabBar(
tabs: [
Text("Account"),
Text("Activity"),
Text("Links"),
],
),
),
body: TabBarView(
children: [
accountStream(),
activityStream(),
linksStream()
]
)
),
);
}
}
我已经尝试解决
我一开始以为是连接错误,所以根据switch (snapshot.connectionState)创建了一系列案例。我可以看到 ConnectionState.active = true 所以认为在 Firestore 中添加新文档可能会产生效果,但什么也没做。
我尝试了以下方法来使初始流构造函数异步。它无法加载任何数据。
Stream<QuerySnapshot> provideActivityStream() async* {
await Firestore.instance
.collection("users")
.document(widget.userId)
.collection('activities')
.orderBy('startDate', descending: true)
.snapshots();
}
我尝试删除 tabcontroller 元素 - 例如只有一个页面 - 但这也无济于事。
我尝试使用DocumentSnapshot 和QuerySnapshot 访问数据。我两个都有问题。
我确信这很简单,但坚持下去。非常感谢任何帮助。谢谢!
【问题讨论】:
-
尝试传递 provideStravaActivityStream 作为对流的引用。
-
您介意发布整个小部件树的代码吗?
-
@Neeraj 我已经编辑了这个问题。希望能给你更多的背景。它在 tabcontroller 中,但我不认为这是错误所在(因为我尝试将它作为独立页面加载并遇到同样的问题)。
-
@AbdelbakiBoukerche 感谢您发现错字。我已编辑问题以显示名称始终为
provideActivityStream。如果我引用了错误的流,我将永远不会获得数据,但我会在重新加载事件中获得数据。 -
@heymonkeyriot 我的意思是使用 stream: provideActivityStream 而不是 stream: provideActivityStream()。
标签: flutter dart google-cloud-firestore stream-builder