Search code examples
flutterflutter-layoutflutter-image

onError method of DecorationImage() in Flutter


Code works fine but because of my unreliable internet connection I am faced with an issue of NetworkImage.load ( See error image below )

Container(
 width: 60,
 height: 80,
 decoration: BoxDecoration(
  color: Colors.black12,
  borderRadius: BorderRadius.all(Radius.circular(7.0))
  image: DecorationImage(
   image: NetworkImage(trend['imageUrl']),
   onError: <how we can handle this?>,
   fit: BoxFit.cover
  ),
 ),
);

I hope this issue can be fixed by handling it on onError method (Correct me if I'm wrong). But I can't figure it out how to do that.

Error: Error I got on Android Studio


Solution

  • First of all lets say you intialize NetworkImage inside your class. like:

    var imgVariable = NetworkImage(trend['imageUrl']);
    

    Then, load your network image. If, error occurs then we will load from our assets to let user know that we could not load network image.

    Container(
     width: 60,
     height: 80,
     decoration: BoxDecoration(
      color: Colors.black12,
      borderRadius: BorderRadius.all(Radius.circular(7.0))
      image: DecorationImage(
       image: imgVariable,
       onError: (errDetails){
           setState(){
               imgVariable = AssetImage('assets/could_not_load_img.jpg');
           };
       },
       fit: BoxFit.cover
      ),
     ),
    );
    

    Here, assets/could_not_load_img.jpg is image that is imformative sthg.

    *Note: This may not seem to work with errors, but this can be a way I came up with. There are plugins like cached_network_image to work beautifully on network images.