我在 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 例外,還適用于任何網路連接錯誤。
例外來源(顫振檔案:).../_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();
}
}
我想知道這是一個錯誤還是我犯了一個錯誤。
uj5u.com熱心網友回復:
是的,您對實施是正確的。所以問題是,NetworkImage 嘗試加載影像并且無法加載它。因此,該_loadAsync()方法rethrows例外。現在,正如您所提供errorBuilder的,框架使用該小部件來顯示例外發生的時間。因此,您將得到一個例外,該例外從框架中重新拋出,但按照您提供的方式處理errorBuilder。現在,如果您洗掉它,errorBuilder您將在除錯控制臺中記錄例外,并且用戶將能夠在除錯模式下看到紅色例外螢屏,在發布模式下看到灰色螢屏。
因此,您對實作以及您的疑問都是正確的,但您錯過了errorBuilder.
我希望這能澄清你的疑問!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/430219.html
