【问题标题】:Flutter still loading network image even though i have a null check即使我有一个空检查,Flutter 仍在加载网络图像
【发布时间】:2021-10-18 19:41:15
【问题描述】:

在我的颤振应用程序中,我将来自 Firebase 存储的 URL 存储在 Firestore 中。我预计会有空 URL,因为它取决于用户上传图像。在我的代码中,我正在检查空值,但由于某种原因,代码仍然尝试加载空值。如何正确防止颤振加载网络图像中的空值。我的加载代码如下:

Container(
  width: 150,
  height: 150,

  child: ListView.builder(
    scrollDirection: Axis.horizontal,
      padding: const EdgeInsets.all(8),
      itemCount: photoList.length,
      itemBuilder: (BuildContext context, int index) {

        print(photoList[index]);

      return photoList[index] != null ? Image.network(photoList[index]) : Container(height:400,child: Text('No Images to Display'));
        
      }
  ),
),

当没有图像时,上面的打印调试如下:

I/flutter (27038): url - null

当有图像时,就会有一个正确的 URL,并且图像加载没有任何问题。

所以不太清楚为什么 Flutter 仍在尝试加载 null,即使在 null 的情况下我想要一个文本框来代替

【问题讨论】:

    标签: flutter google-cloud-firestore firebase-storage


    【解决方案1】:

    看起来您的photoList[index] 值不一致。由于它在预期包含空值且不为空时打印“url - null”,因此它包含加载图像的实际 url。

    您可以选择以下任一方式:

    • 确保您的 null 图像实际上是 null 而不是“url - null”,并且 null 检查将起作用。

    • 使用Image.network 小部件的errorBuilder 属性来显示您的错误小部件,如下所示:

      Image.network(photoList[index],
        errorBuilder: (context, error, stackTrace) {
          return Container(height:400,child: Text('No Images to Display'));
        }
      )
      

    【讨论】:

    • 谢谢。 URL 为空,但由于某种原因,逻辑检查不起作用。我已经测试了errorBuilder,这似乎工作得很好。您也是正确的,即使我已将它作为空值写入 Firestore,空值也作为字符串传递。从未想过将检查设为“空”。非常感谢您指出这一点。
    • 好的,很高兴知道它成功了。好吧,理想情况下,null 值实际上应该是 null 而不是字符串“null”。您应该仔细检查写入操作。在此处查看 Firestore 支持的数据类型:firebase.google.com/docs/firestore/manage-data/data-types
    【解决方案2】:

    photoList 中存储什么类型的数据?如果String 有可能“null”值实际上是一个字符串,而不是null

    【讨论】:

    • 道歉。我在编写此语句以更新输出时更新了print 语句。我当前代码中的打印语句是print('url - ${photoList[index]}');
    猜你喜欢
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 2020-06-03
    • 2021-06-06
    • 1970-01-01
    相关资源
    最近更新 更多