Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm using the cached_network_image library. If I set it up like this:

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),
       ),
      ),
    );
  }
}

with a URL that is invalid (either because it returns a 404 or the server refuses the connection), then my IDE freezes and gives one of the following errors:

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

or this (if I change it to a non-existent host):

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

enter image description here

What I would expect is for the CachedNetworkImage widget to just show the errorWidget, but it doesn't.

like image 693
Suragch Avatar asked Jan 15 '21 08:01

Suragch


1 Answers

I also experienced this issue, and could not find a flutter way to solve the 404 issue which crashes the app.

As a solution, I am using imagekit as a CDN and we can tell imagekit to display a default image if the original image is missing: https://docs.imagekit.io/features/default-images

like image 122
Kng1230 Avatar answered Nov 15 '22 06:11

Kng1230