I am scraping some images from any kind of websites. And I need to calculate their Size
. For that I found that function
which is working for most of the cases:
Future<Size> calculateImageDimension(String imageUrl) {
Completer<Size> completer = Completer();
late Image image;
image = Image.network(
imageUrl,
);
image.image.resolve(const ImageConfiguration()).addListener(
ImageStreamListener(
(ImageInfo image, bool synchronousCall) {
var myImage = image.image;
Size size = Size(myImage.width.toDouble(), myImage.height.toDouble());
if (!completer.isCompleted) {
completer.complete(size);
}
},
),
);
return completer.future;
}
Problem:
The function above fails with
Exception: Invalid image data
when calling it with this imageUrl
:
https://static.zara.net/photos///contents/cm/media-transformations/joinlife-ctx/joinlife-large.svg?ts=1611919362013
What's the issue here? Also I couldn't catch
the Exeption
...
I found this related question. But its not helping me either.
CodePudding user response:
I found this issue on Git and it works for my quite well. It is rather a workaround than a solution:
Future<bool> hasValidImageData(String url,BuildContext context) async {
bool hasNoError=true;
var output=Completer<bool>();
precacheImage(
NetworkImage(url),
context,
one rror: (e,stackTrace)=>hasNoError=false,
).then((_)=>output.complete(hasNoError));
return output.future;
}
it makes use of the onError
that precacheImage
come with. A downside is that it needs the BuildContext
but like I said, its working for me and the only workaround I found.