【问题标题】:Flutter why does futureBuilder consider null firestore document as not null?Flutter 为什么futureBuilder 认为null firestore 文档不为null?
【发布时间】:2021-03-15 14:04:30
【问题描述】:
 FutureBuilder(future: Firestore.instance
            .collection('items')
            .document('itemId')
            .collection('sold')
            .document('sold')
            .get(),
            builder: (context, snapshot){
              return (snapshot != null) ? Text(
                '${snapshot.data['sold']}'
              ) : Text('not sold');}

我在这里使用 futureBuilder 编写了这段代码,希望小部件在 firestore 上“已售”文档的“已售”字段还没有值时显示“未售出”(“已售”文档尚未创建)。

但是当很明显snapshot为null的时候,由于没有创建document,它继续执行ternary的第一个选项,并尝试输出'${snapshot.data['sold']}',显示这个错误

The method '[]' was called on null.
Receiver: null
Tried calling: []("sold")

似乎它将“${snapshot.data['sold']}' 中的“snapshot.data”作为 null,这是正确的,因为尚未创建文档,但我不知道为什么它不考虑来自 '(snapshot != null)' 的快照不为空。

当创建了“sold”文档并且它不为空时,它会在屏幕上显示 '${snapshot.data['sold']}' 值。

只有三元在这里不起作用..

我搜索它并尝试使用“(snapshot.hasdata)”而不是“(snapshot != null)”,但没有任何改变。

我在这里做错了什么?

PS - 似乎文档实际上是空的,但不知何故认为它不是空的。我不知道这是否是 firestore 方面的问题,或者可能是 futureBuilder 被构建为使用一些初始数据状态进行初始化..

【问题讨论】:

  • 我没有。我刚刚重新格式化了代码。

标签: flutter google-cloud-firestore


【解决方案1】:
builder: (context, snapshot){
          return (snapshot.data != null) ? Text(
            '${snapshot.data['sold']}'
          ) : Text('not sold');}

另一种方法是:

builder: (context, snapshot){
          return (snapshot.hasData) ? Text(
            '${snapshot.data['sold']}'
          ) : Text('not sold');}

您也可以检查错误,也许这就是缺少的内容

builder: (context, snapshot){
          if (snapshot.hasError) return Text("Error");
          if (snapshot.hasData) return Text(snapshot.data['sold']);
          // else return a progress indicator
          return CircularProgressIndicator();
}

【讨论】:

  • 使用“snapshot.data”和“snapshot.hasData”给出相同的结果。不知何故,它认为空数据不为空。这就是问题所在..
  • @AndyYoung 我用另一个代码 sn-p 更新了答案,希望这个有效,你可以找到问题
【解决方案2】:

我同意 Omar,您可以尝试这种方式,甚至可以尝试以下方式

builder: (context, snapshot){
              return (snapshot.hasData && snapshot.data != null && snapshot.data.lenght > 0) ? Text(
                '${snapshot.data['sold']}'
              ) : Text('not sold');}

【讨论】:

  • 没什么区别。我认为问题在于它认为空数据不是空的......有什么想法吗?
  • 我认为您首先应该确保您的 futurebuilder 为空。你试过打印吗?了解它的内容可能是个好主意,然后您可以验证它为什么具有该值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-22
  • 2021-10-08
  • 2020-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多