Tryliom
Tryliom

Reputation: 953

Flutter - How to catch an error when call a picture with a bad url with Image.Network

I tried to call a picture with a bad url and show an image when failed... but flutter throw an exception and try catch not working during run development.

var url = "http://badUrl.com"
try {
    return Image.network(
            url,
            width: pictureSize.width,
            height: pictureSize.height,
            fit: BoxFit.fitWidth,
            errorBuilder: (BuildContext context, Object exception,
                StackTrace stackTrace) {
              return Image.asset("assets/img/logo.png");
            },
    );
} catch (error) {
  return Image.asset("assets/img/logo.png");
}

I have already try that but it doesn't working

Upvotes: 1

Views: 497

Answers (2)

Sayanc2000
Sayanc2000

Reputation: 222

If you want a comprehensive solution to this you can use cached_image widget https://pub.dev/packages/cache_image

This will help you out with a lot of exception cases

Upvotes: 0

user14789593
user14789593

Reputation:

Maybe you should adapt the canLaunch method which verify if your link is valid, to your example

if (canLaunch(url) != null) {
  launch(url);
} else {
  throw 'Could not launch $url';
}

Upvotes: 1

Related Questions