Sometimes my image URLs are not available, or load fails for some other reason (like being offline).
When that happens my CachedNetworkImageProvider
is throwing SocketException: Failed host lookup.
But I don’t want it to throw, I just would like to see an empty placeholder there in that case.
(like the Image
equivalent of a Container()
)
-
I can’t use
CachedNetworkImage
(which has an error placeholder widget param) because anImageProvider
is required, rather than anImage
. -
I can’t use the
Image.image
parameter as theCachedNetworkImage
doesn’t support that. -
I’ve added
<uses-permission android:name="android.permission.INTERNET"/>
to myAndroidManifest.xml
– that isn’t the problem. -
I tried wrapping the widget in a try – catch, like the following but that doesn’t do anything (ie. the throw still occurs and it never reaches the catch block):
import 'package:cached_network_image/cached_network_image.dart';
cachedNetworkImageProviderThatDoesntCrash(String url) {
try {
return CachedNetworkImageProvider(url);
} catch (e) {
return null;
}
}
-
I tried extending
CachedNetworkImageProvider
but got stuck figuring out exactly what needed to be overriden. -
I tried cloning
CachedNetworkImageProvider
but then I need to add a whole bunch of other includes in my project … it just was a very messy approach.
An easy solution would be if there was a way to wrap the CachedNetworkImage
in something that converts it into a CachedNetworkImageProvider
.
All I’m wanting to achieve is for the thing to not throw when there is any error loading the CachedNetworkImageProvider
url.
Update
I seem to hit this situation frequently – I realise it can be solved by a simple mechanism of converting between Image
and ImageProvider
, and visa versa, with the caveat that it would also work for CachedNetworkImage
and CachedNetworkImageProvider
.
2
Answers
Image
widget has anerrorBuilder
parameter.You can use it to show placeholder images either from
network
orasset
if an exception exists.You can go to the official CachedNetworkImage github repo here and fork it. Then go to the path in this image and comment(or delete) the rethrow statement in that file.
Go to your pubspec.yaml file and import the CachedNetworkImage from your repository like so: