【问题标题】:Getting a valid value from StreamBuilder<DocumentSnapshot> and a child StreamBuilder从 StreamBuilder<DocumentSnapshot> 和子 StreamBuilder 获取有效值
【发布时间】: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 不会在其父级出于优化目的进行重建时进行重建,但我决不能确定这一点。你可以在调试器中弹出你的程序,看看是不是这样。
  • 如果是这种情况,您可以使用StatefulWidgetsetState 来解决问题,或者使用来自 RxDart 的流操作之一将流合并为一个(因此只有有一个StreamBuilder,然后总是会重建)。

标签: flutter dart


【解决方案1】:

我遇到的问题是,即使数据库中没有要返回的内容,Cloud Firestore 也会返回 DocumentSnapshot。因此,我将 (snapshot1.hasData) 更改为 (snapshot1.data.exists),这按预期工作 - 图标会根据响应而变化。

【讨论】:

    猜你喜欢
    • 2021-02-26
    • 2020-09-27
    • 1970-01-01
    • 2019-04-13
    • 2021-02-20
    • 2020-01-17
    • 2020-08-08
    • 1970-01-01
    • 2020-06-24
    相关资源
    最近更新 更多