Flutter - Default image to Image.network when it f

2019-05-22 20:10发布

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

2条回答
forever°为你锁心
2楼-- · 2019-05-22 20:24

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,
  );
}
查看更多
女痞
3楼-- · 2019-05-22 20:42

You can do with FadeInImage.assetNetwork

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

and in pubspec.yaml

  assets:
  - assets/place_holder.jpgT
查看更多
登录 后发表回答