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?
I achieved this by using
precacheImage
. This will precache your image to flutter cache. It also has aonError
function where you can handle errors while caching the image.Then
validatedUrl
is either null, empty or carries the validated url.null
-> not validated yetempty
-> error while downloading imageurl
-> successfully downloaded image