【问题标题】:How to catch a FetchFailure Exception in Flutter for image URLs that 404?如何在 Flutter 中为 404 的图像 URL 捕获 FetchFailure 异常?
【发布时间】:2018-10-04 01:10:05
【问题描述】:

我有这样的事情:

try {
    final image = NetworkImageWithRetry(url,
        fetchStrategy: FetchStrategyBuilder(
            timeout: Duration(seconds: 2),
            transientHttpStatusCodePredicate: (code) {
              return code == null ||
                  FetchStrategyBuilder
                      .defaultTransientHttpStatusCodePredicate(code);
            }).build()
        );
      return Padding(
        padding: EdgeInsets.all(10.0),
        child: Image(
          image: image,
        ),
      );
  } catch FetchFailure {
    print('exception!');
    return Container();
  }

对于不存在的图片,图片多次尝试加载,总是抛出:

EXCEPTION CAUGHT BY PACKAGE:FLUTTER_IMAGE
The following FetchFailure was thrown NetworkImageWithRetry failed to load

我如何捕捉到这个?我试过catch Exceptioncatch FetchFailurecatch (error)

我也尝试过根据错误代码返回一个小部件,但 FetchStrategyBuilder 希望我返回一个布尔值。

【问题讨论】:

  • 服务器返回404时你想发生什么?放弃并显示一个空/空图像?
  • 更新了问题 - 如果图像成功返回,我想用填充返回图像。否则,我想返回一个空容器(没有额外的填充)。
  • @RichardHeap 不用问他下一步想做什么。问题很简单。如何捕捉错误

标签: image networking dart flutter


【解决方案1】:

您无法捕获 FetchFailure 错误的原因是它已在 flutter_image 中捕获。您收到的错误消息中指出了这一点:EXCEPTION CUGHT BY PACKAGE:FLUTTER_IMAGE

您能否提供更多详细信息,说明您为何尝试捕获异常?如果原因是您尝试显示占位符图像以防图像加载失败,您可以使用FadeInImageCachedNetworkImage

【讨论】:

    猜你喜欢
    • 2010-12-01
    • 1970-01-01
    • 2012-11-08
    • 2020-08-13
    • 2020-06-17
    • 2022-11-20
    • 2012-05-08
    • 1970-01-01
    • 2021-08-22
    相关资源
    最近更新 更多