Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - Default image to Image.network when it fails

Is there any way you can control exceptions launched by Image.network() so you can provide it a default AssetImage ?

like image 452
Jesús Martín Avatar asked Apr 11 '18 09:04

Jesús Martín


2 Answers

It depends on your use case, but one way to do it is to use FadeInImage which has a property of img for the image that is intended to load, and placeholder, well, for the placeholder

FadeInImage(image: NetworkImage(url), placeholder: AssetImage(assetName)

You can also listen until the image is loaded and show a placeholder yourself until fetching the image resolves.

pseudo code

bool _loaded = false;
var img = Image.network(src);
var placeholder = AssetImage(assetName)

@override
void initState() {
  super.initState();
  img.image.resolve(ImageConfiguration()).addListener((i, b) {
    if (mounted) {
      setState(() => _loaded = true);
    }
  });     
}

@override
Widget build(BuildContext context) { 
  return YourWidget(
    child: _loaded ? img : placeholder,
  );
}
like image 185
Shady Aziza Avatar answered Oct 24 '22 10:10

Shady Aziza


You can do with FadeInImage.assetNetwork

 child: new Container(
      child: FadeInImage.assetNetwork(
          placeholder: 'assets/place_holder.jpg',
          image:url
      )
  )

and in pubspec.yaml

  assets:
  - assets/place_holder.jpg
like image 26
Lay Leangsros Avatar answered Oct 24 '22 08:10

Lay Leangsros