gpt4 book ai didi

android - 即使在 Flutter 中定义了 errorBuilder,Image.network 也会抛出错误

转载 作者:行者123 更新时间:2023-12-04 23:45:36 31 4
gpt4 key购买 nike

我在 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 不存在,小部件会抛出 404 异常,即使 errorBuilder参数已定义。它不仅适用于 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异常(exception)。现在,正如您提供的 errorBuilder ,框架使用该小部件来显示异常发生的时间。因此,您将得到一个异常,该异常从框架中重新抛出,但按照您提供的 errorBuilder 进行处理。 .现在,如果您删除 errorBuilder如果在 Debug模式下,您将在调试控制台中记录异常,并且用户将能够看到红色异常屏幕,而在 Release模式下则可以看到灰色屏幕。
因此,您对实现以及您的疑问都是正确的,但是您错过了 errorBuilder 的确切解释.
我希望这能澄清你的疑问!

关于android - 即使在 Flutter 中定义了 errorBuilder,Image.network 也会抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71205799/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com