Flutter - How to catch Image.network error when there is no image in the link

Viewed 382

Can you help resolve how to catch the exception when the image does not exist in the url given in Image.network widget. I tried it with errorBuilder property..but still throws an exception.

       Expanded(
        child: Image.network(
         imageUrl,
         width: 50,
         height: 250,
         fit: BoxFit.fill,
         errorBuilder: (context, exception, stackTrack) => Icon(Icons.error,),
        ))

When goes to the image link that throws the exception, it shows as below:

 {
  "error": {
    "code": 404,
    "message": "Not Found.  Could not get object",
    "status": "GET_OBJECT"
   }
 }

imageUrl link is taken from array of data loaded from Firabase as below

 Future<void> loadData() async {
  QuerySnapshot querySnapshot;
  try {
    querySnapshot = <gets data from firebase>
    querySnapshot.docs.forEach((result) {
      arr.add(result.data()); //adds data into an array
    });
  } catch (e) {
      print(e);
  }
}
1 Answers

You can use error builder as following

errorBuilder: (context, error, stackTrace) {
   return Image.asset(
             'assets/images/image_not_found.png',
              width: 300, 
              height: 200, 
              fit: BoxFit.contain
   );
}

OR

errorBuilder: (context, error, stackTrace) {
          return Icon(Icons.error);
        }
Related