Flutter - How to convert an NetworkImage into an ui.Image?

Viewed 689

I need to convert a NetworkImage to an ui.Image. I tried to use the given solution from this question with some adjusts but it isn't working.

Someone can help me?

 Uint8List yourVar;
 ui.Image image;
    final DecoderCallback callback =
        (Uint8List bytes, {int cacheWidth, int cacheHeight}) async {
      yourVar = bytes.buffer.asUint8List();
      var codec = await instantiateImageCodec(bytes,
          targetWidth: cacheWidth, targetHeight: cacheHeight);
      var frame = await codec.getNextFrame();
      image = frame.image;
      return image;
    };
    ImageProvider provider = NetworkImage(yourImageUrl);
    provider.obtainKey(createLocalImageConfiguration(context)).then((key) {
      provider.load(key, callback);
    });
1 Answers

first create a field in your class:

var cache = MapCache<String, ui.Image>();

then to get ui.Image you can simply call:

var myUri = 'http:// ...';
var img = await cache.get(myUri, ifAbsent: (uri) {
  print('getting not cached image from $uri');
  return http.get(uri).then((resp) => decodeImageFromList(resp.bodyBytes));
});
print('image: $img');

of course you should add some http response error handling but this is the base idea...

Related