Search code examples
flutterdartflutter-image

How I can show a image from network, but if there is something wrong I want to show an image from app assets


let's say I have this

String imageNetworkLink = someUnstableLink;

I want to be able to show that image in my flutter app if it's working, otherwise I want to show an image from my assets.

I tried using Image.asset() and AssetImage() and Image.network() but none of theme accepts a netork link and asset path link

I'm expecting to show either a link from network, if there is a problem, I want to show an image from asset


Solution

  • This is what you are looking for: https://pub.dev/packages/cached_network_image

    Usage:

    CachedNetworkImage(
         imageUrl: "http://some_image_on_the_internet.png",
         // Some widget to display while the network widget is loading
         //It could be any widget
         placeholder: (context, url) => Image.asset(''),
         // Some widget to display if the network image was unable to load
         // This could be because of loss of internet connection
         errorWidget: (context, url, error) => Icon(Icons.error),
         ),
    

    For your usecase, You may only need to implement imageUrl which is required and errorWidget, for when something goes wrong