How to catch "Unable to load asset: assets/images/sample_img_url.png" How to catch "Unable to load asset: assets/images/sample_img_url.png" flutter flutter

How to catch "Unable to load asset: assets/images/sample_img_url.png"


Okay, finally I found a really nice way to overcome this issue. Just use an error builder.

Image.asset(     "assets/images/subjects/api_given_image_name.png",     width: 90,     errorBuilder: (BuildContext context, Object exception, StackTrace stackTrace) {           return Image.asset(                "assets/images/your_sample_image.png",                width: 90,           );     },)


You have to define the asset path in pubspec.yaml like the followings :

flutter:  assets:    - assets/my_icon.png    - assets/background.png

To include all assets under a directory, specify the directory name with the / character at the end:

flutter:  assets:    - directory/    - directory/subdirectory/

Official doc :https://flutter.dev/docs/development/ui/assets-and-images


I think the error should not be resolved in the runtime. So specify only existing image paths. In case you have no image in specified path you should not use it.

BUT. If you still want to catch the exception firstly you should understand that Image.asset works asynchronously. Exception throws later, that's why you can't catch it. Take a look at this GitHub issue, hope it helps.