【发布时间】:2021-01-02 18:41:22
【问题描述】:
我在下面得到了这段代码,我在这里面临的问题是,至少在页面加载时,connectionState 似乎总是显示“false”。 我在 Firestore 上有“myValue”值,在“items”的子集合“subItem”下,有些项目已经创建了这个 subCollection 并且 hasData 但有些没有。
Widget build(BuildContext context) {
return StreamBuilder(
stream:Firestore.instance
.collection('other')
.document(documentID)
.snapshots(),
builder: (context, streamSnapshot1) {
return StreamBuilder(
stream: Firestore.instance
.collection('items')
.document(documentID)
.collection('subItems')
.document(userUID)
.snapshots(),
builder: (context, streamSnapshot2) {
return _detailPage(context, streamSnapshot2)
});
}
});
}
Widget _detailPage(context, streamSnapshot1, streamSnapshot2) {
var myValue = (streamSnapshot2.connectionState != true) ? 1
: (streamSnapshot2.hasData) ? streamSnapshot2.data['myValue']: 2;
print(myValue);
return Scaffold(etc)
}
在这种情况下,“myValue”总是打印“1”。它是否对 Firestore 有价值。当我打印connectionState时,它会显示“connectionState.waiting”一段时间,然后更改为“connectionState.active”。最初显示的 'connectionState.waiting' 是 firestore 流的已知行为,但即使将其更改为活动状态,它仍然会考虑 'streamSnapshot2.connectionState != true' 并返回 '1'。是否应该将“connectionState.done”视为“streamSnapshot2.connectionState == true”?但它永远不会更改为“connectionStat.done”。
当我尝试不使用 'connectionState' 并且仅使用 hasData 进行检查时,
var myValue = (streamSnapshot2.hasData) ? streamSnapshot2.data['myValue']: 2;
当项目中已经有“subItems”子集合和数据时,它可以显示存储在 firestore 上的“myValue”的正确值。但在这种情况下,应用程序会在尚未创建“subItem”子集合的项目中中断。带有以下错误消息。
error: The method '[]' was called on null.
这是因为 'streamSnapshot.data' 仍然为空。我也无法理解这一点,因为虽然没有数据,因此它为空,但它通过了 (streamSnapshot2.hasData == true) 条件。
这里有什么问题?
【问题讨论】:
标签: flutter google-cloud-firestore