Flutter CachedNetworkImage 错误:(CacheManager:无法下载文件)和(SocketException 或 HttpException)

Flutter CachedNetworkImage errors: (CacheManager: Failed to download file) and (SocketException or HttpException)

我正在使用 cached_network_image 库。如果我这样设置:

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print('MyApp building');
    return MaterialApp(
      home: Scaffold(
        body: HomeWidget(),
      ),
    );
  }
}

class HomeWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        child: CachedNetworkImage(
          imageUrl: "https://example.com/image/whatever.png",
          placeholder: (context, url) => CircularProgressIndicator(),
          errorWidget: (context, url, error) => Icon(Icons.error),
       ),
      ),
    );
  }
}

使用无效的 URL(因为它 returns 404 或服务器拒绝连接),然后我的 IDE 冻结并给出以下错误之一:

HttpExceptionWithStatus (HttpException: Invalid statusCode: 404, uri = https://example.com/image/whatever.png)

或者这个(如果我把它改成一个不存在的主机):

SocketException (SocketException: Failed host lookup: 'ksdhfkajsdhfkashdfkadshfk.com' (OS Error: No address associated with hostname, errno = 7))

我希望 CachedNetworkImage 小部件只显示 errorWidget,但它没有。

cached_network_image says (source 的创建者):

If you have break on exceptions enabled the debugger stops, but that's because the dart VM doesn't always know whether an exception is caught or not. If you continue this still shouldn't freeze your app.

那是我需要的钥匙。这只是调试器停止。您可以点击继续按钮或禁用停止未捕获的异常。 CachedNetworkImage 小部件将按预期显示 errorWidget

在 VS Code 中,您可以在调试面板的左下方取消选中此选项。

我相信 Android studio 中有一个基于 this post 的类似设置。

我也遇到过这个问题,一直找不到flutter解决404崩溃的办法

作为解决方案,我使用 imagekit 作为 CDN,如果原始图像丢失,我们可以告诉 imagekit 显示默认图像:https://docs.imagekit.io/features/default-images