fluttererror-handlingtry-catchflutter-assetimage

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


Is there any way to catch the "Unable to load asset: assets/images/sample_img_url.png" error in Flutter?

What I am trying to do is load an asset image by providing its path(from API). But if I do not have an image that associates with the given path, I need to load a sample image.

I've created a custom placeholder widget as follows. But's it's not working as I expected. anyone can help me with this?

class ImagePlaceHolder extends StatelessWidget {
  final String path;
  final double width;

  const ImagePlaceHolder({Key key, this.path, this.width}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    Image finalImage;
    try{
      finalImage = Image.asset(
          path,
          width: width,
      );
    }
    catch(Exception){
      finalImage = Image.asset(
          "assets/images/app_update_logo.png",
          width: width,
      );
    }
    return finalImage;
  }
}

Solution

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