简体   繁体   中英

Flutter NetworkImage handle 403 error

In my Flutter mobile app while loading profile image of users through NetworkImage() , I am getting 403 status code in response.

How can I handle this by displaying an Image from my assets folder in case of 403 status code or if image URL is broken etc.

Currently I've handled it by sending a HTTP GET request to the image URL and checking if the status code is 200 . If it is 200 I use the NetworkImage() or else I use AssetImage() to load the image and use a FutureBuilder() to build the Widget.

While this works perfectly, I feel this a lot of trouble for handling such a small scenario and it can be done in a better way that I am unaware of.

What is the best way to handle such scenarios?

You did it simple for this scenario, I didnt see any trouble:

  if (response.statusCode == 200) {
    return NetworkImage();
  } else {
    return AssetImage();
  }

I achieved this by using precacheImage . This will precache your image to flutter cache. It also has a onError function where you can handle errors while caching the image.

String validatedUrl;

precacheImage(
  NetworkImage(urlToCheck),
  context,
  onError: (
    exception,
    stacktrace,
  ) {
    print(exception.toString());
    setState(() {
      validatedUrl = '';
    });
  },
).whenComplete(() {
  if (validatedUrl == null) {
    setState(() {
      validatedUrl = urlToCheck;
    });
  }
});

Then validatedUrl is either null, empty or carries the validated url.

  • null -> not validated yet
  • empty -> error while downloading image
  • url -> successfully downloaded image

Please try below approach. Here, If image is available, It will load network image else it will redirect to the error callback. In error callback you can return the widget you want. In your case, you want to load from asset so you can use it like as below. If you want to check error status code, you need to parse the exception that I have print.

 Image.network('https://www.outbrain.com/techblog/wp-content/uploads/2017/05/road-sign-361513_960_720.jpg',
            errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) {
            print("Exception >> ${exception.toString()}");           
              return Image.asset('assets/images/lake.jpg');
            },
          )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM