Flutter - Default image to Image.network when it fails
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,
);
}
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