簡體   English   中英

即使在 Flutter 中定義了 errorBuilder 之后,Image.network 也會拋出錯誤

[英]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();
    }
  }

我想知道這是一個錯誤還是我犯了一個錯誤。

我已經使用 errorBuilder 處理了與 404 相關的網絡圖像問題。

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

是的,您對實施是正確的。 所以問題是,NetworkImage 嘗試加載圖像並且無法加載它。 因此, _loadAsync()方法會rethrows引發異常。 現在,正如您提供的errorBuilder ,框架使用該小部件來顯示何時發生異常。 因此,您會得到一個異常,該異常是從框架中重新拋出的,但會按照您提供errorBuilder進行處理。 現在,如果您刪除errorBuilder ,您將在調試控制台中記錄異常,並且用戶將能夠在調試模式下看到紅色異常屏幕,在發布模式下看到灰色屏幕。

因此,您對實現以及您的疑問都是正確的,但是您錯過了errorBuilder的確切解釋。

我希望這能澄清你的疑問!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM