Image.network 即使在 Flutter 中定义了 errorBuilder 之后也会抛出错误

Image.network throw error even after defining errorBuilder in Flutter

我在 Flutter 中从 URL 加载图片时遇到了一些问题。这是我的代码:

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(8.0),
      child: Center(
        child: Image.network(
          'https://www.example.com/no-image.jpg', // this image doesn't exist
          fit: BoxFit.cover,
          errorBuilder: (context, error, stackTrace) {
            return Container(
              color: Colors.amber,
              alignment: Alignment.center,
              child: const Text(
                'Whoops!',
                style: TextStyle(fontSize: 30),
              ),
            );
          },
        ),

      ),
    );
  }

我正在使用 Image.network 从给定的 URL 接收图像,但由于 URL 不存在,即使 errorBuilder 小部件抛出 404 异常参数被定义。它不仅适用于 404 异常,还适用于任何网络连接错误。

异常来源(flutter文件:.../_network_image_io.dart):

Future<ui.Codec> _loadAsync(
    NetworkImage key,
    StreamController<ImageChunkEvent> chunkEvents,
    image_provider.DecoderCallback decode,
  ) async {
    try {
      assert(key == this);

      final Uri resolved = Uri.base.resolve(key.url);

      final HttpClientRequest request = await _httpClient.getUrl(resolved);

      headers?.forEach((String name, String value) {
        request.headers.add(name, value);
      });
      final HttpClientResponse response = await request.close();
      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>>(<int>[]);
        throw image_provider.NetworkImageLoadException(
            statusCode: response.statusCode, uri: resolved);
      }

      final Uint8List bytes = await consolidateHttpClientResponseBytes(
        response,
        onBytesReceived: (int cumulative, int? total) {
          chunkEvents.add(ImageChunkEvent(
            cumulativeBytesLoaded: cumulative,
            expectedTotalBytes: total,
          ));
        },
      );
      if (bytes.lengthInBytes == 0)
        throw Exception('NetworkImage is an empty file: $resolved');

      return decode(bytes);
    } catch (e) {
      // Depending on where the exception was thrown, the image cache may not
      // have had a chance to track the key in the cache at all.
      // Schedule a microtask to give the cache a chance to add the key.
      scheduleMicrotask(() {
        PaintingBinding.instance!.imageCache!.evict(key);
      });
      print(e);
      rethrow; // <<<<<<<< Exception throw here: NetworkImageLoadException (HTTP request failed, statusCode: 404, https://www.example.com/no-image.jpg)
    } finally {
      chunkEvents.close();
    }
  }

我想知道这是一个错误还是我弄错了。

是的,您的实现是正确的。所以问题是,NetworkImage 尝试加载图像但加载失败。因此,_loadAsync() 方法 rethrows 例外。现在,正如您提供的 errorBuilder,框架使用该小部件来显示异常发生的时间。因此,您会收到一个从框架中重新抛出的异常,但会按照您提供的方式进行处理 errorBuilder。现在,如果您删除 errorBuilder,您将在调试控制台中记录异常,如果处于调试模式,则用户将能够看到红色异常屏幕,而在发布模式中,则将看到灰色屏幕。

所以,你的实现和你的怀疑都是正确的,但是你错过了 errorBuilder 的确切解释。

希望这能解开你的疑惑!