【问题标题】:Cannot catch NetworkImageLoadException when Image.network() failedImage.network() 失败时无法捕获 NetworkImageLoadException
【发布时间】:2021-07-06 17:47:38
【问题描述】:

我使用 Image.network() 从 URL 显示图像 我就是这样用的

Image image = Image.network(
      _auth.currentUser!.photoURL!,
      width: 100.getWidth(context),
      height: 100.getWidth(context),
      frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
        return wasSynchronouslyLoaded
            ? child
            : _profileImagePlaceholder(context);
      },
      loadingBuilder: (context, child, loadingProgress) {
        return loadingProgress == null
            ? child
            : _profileImagePlaceholder(context);
      },
      errorBuilder: (context, error, stackTrace) {
        return _profileImagePlaceholder(context);
      },
    );

但即使我设置了 errorBuilder 甚至用 try/catch 包装了整个东西 这个NetworkImageLoadException 还在显示

完全例外

The following NetworkImageLoadException was thrown resolving an image codec:
HTTP request failed, statusCode: 403,


When the exception was thrown, this was the stack:
#0      NetworkImage._loadAsync (package:flutter/src/painting/_network_image_io.dart:99:9)
<asynchronous suspension>
...

Image provider:
  NetworkImage("https://firebasestorage.googleapis.com/v0/b/biddee-co.appspot.com/o/profiles%2FdefaultProfile.png?alt=media&token=a4a99031-aabd-4597-b075-77ecb2d3e594",
  scale: 1.0)
Image key:
  NetworkImage("https://firebasestorage.googleapis.com/v0/b/biddee-co.appspot.com/o/profiles%2FdefaultProfile.png?alt=media&token=a4a99031-aabd-4597-b075-77ecb2d3e594",
  scale: 1.0)

【问题讨论】:

  • 您找到解决方案了吗?我也有同样的问题。甚至 try/catch 也不做任何事情,应用程序会因为“未捕获的异常”而暂停。

标签: flutter flutter-image


【解决方案1】:

包中:flutter/src/painting/_network_image_io.dart


if (response.statusCode != HttpStatus.ok) {
    // The network may be only temporarily unavailable, or the file will be
    // added on the server later. Avoid having future calls to resolve
    // fail to check the network again.
    await response.drain<List<int>>();
    throw image_provider.NetworkImageLoadException(statusCode: response.statusCode, uri: resolved);
}  

该评论是导致异常的原因。

网络可能只是暂时不可用,或者文件稍后会添加到服务器上。 避免以后调用来解决无法再次检查网络。

【讨论】:

    【解决方案2】:

    您可以为此使用 ErrorBuilder

    Image.network('Your image url...',
        errorBuilder: (BuildContext context, Object exception, StackTrace stackTrace) {
            return Text('Error');
        },
    ),
    

    查找文档from here

    【讨论】:

    • 我已经按照我提到的那样做了,但它仍然给出了异常
    猜你喜欢
    • 2018-09-21
    • 1970-01-01
    • 2016-05-06
    • 2015-12-21
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多