【发布时间】:2020-09-26 21:09:25
【问题描述】:
我正在尝试根据用户是否参加调查来显示特定图标。
目前,我正在使用 StreamBuilder 侦听文档中的给定值,该值返回调查名称。然后,我想在下一个 StreamBuilder 中使用调查名称,它将在给定集合(由调查名称后跟 _entrants - 例如,Survey_entrants 组成)中查找已完成的调查文档,该文档将具有用户唯一 ID 的标题(名为 userid)。
我现在遇到的问题是,虽然surveyName 确实返回了放在 Cloud Firestore 中的调查的名称,并在我更改值时更新它(我可以通过注释掉的 return new Text('$surveyName' ); 命令)。
但是,它似乎没有将该值传递给下一个 StreamBuilder - 无论我输入什么作为调查名称,我都会显示检查图标,建议 (snapshot1.hasData) - 即使该文档没有存在。
我知道surveyName 变量正在工作,但如果我执行snapshot1.toString() 会收到错误Snapshot(ConnectionState.active, 'DocumentSnapshot' 实例,null)。这必须计算有数据,因此显示正在进行的调查。我该如何纠正这个问题?
我的代码:
Positioned(
right: 30,
top: 20,
child: StreamBuilder<DocumentSnapshot>(
stream: Firestore.instance
.collection('Controller')
.document('Current Survey')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<DocumentSnapshot> snapshot) {
if (!snapshot.hasData) {
return CircularProgressIndicator();
} else {
var sn = snapshot.data;
surveyName = sn["cs"];
// return new Text('$surveyName');
return StreamBuilder(
stream: Firestore.instance
.collection('$surveyName' + '_entrants')
.document(userid)
.snapshots(),
builder: (BuildContext context, snapshot1) {
if (!snapshot1.hasData) {
return Icon(
Foundation.burst_new,
size: 48,
color: Color(0xff303841),
);
} else if (snapshot1.hasData) {
return Icon(
Foundation.check,
size: 48,
color: Color(0xff303841),
);
} else {
return Icon(
MaterialIcons.error_outline,
size: 48,
color: Color(0xff303841),
);
}
});
}
})),
【问题讨论】:
-
我的猜测是子
StreamBuilder不会在其父级出于优化目的进行重建时进行重建,但我决不能确定这一点。你可以在调试器中弹出你的程序,看看是不是这样。 -
如果是这种情况,您可以使用
StatefulWidget和setState来解决问题,或者使用来自 RxDart 的流操作之一将流合并为一个(因此只有有一个StreamBuilder,然后总是会重建)。