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)@overridevoid initState() { super.initState(); img.image.resolve(ImageConfiguration()).addListener((i, b) { if (mounted) { setState(() => _loaded = true); } }); }@overrideWidget build(BuildContext context) { return YourWidget( child: _loaded ? img : placeholder, );}
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.jpg
There is a new package called cached_network_image
which does what you need.Here you can set a "loading" image and an "error" image right out of the box.
A flutter library to show images from the internet and keep them in the cache directory. https://pub.dev/packages/cached_network_image#-readme-tab-
CachedNetworkImage( imageUrl: "http://via.placeholder.com/350x150", placeholder: (context, url) => new CircularProgressIndicator(), errorWidget: (context, url, error) => new Icon(Icons.error), ),
or you can use your own asset image as a placeholder for example:
...placeholder: (context, url) => {return Image.asset('assets/img/my_placeholder.png');},
Add this to your package's pubspec.yaml file:
dependencies: cached_network_image: ^1.1.1
and import in your dart code:
import 'package:cached_network_image/cached_network_image.dart';