2

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);
    });
JRamos29
  • 880
  • 7
  • 20
  • why not to use [http](https://pub.dev/packages/http) package directly and `decodeImageFromList` top level function? – pskink Jun 05 '20 at 05:49
  • With http i can cache the image? I asked about NetworkImage cause i intend to use CachedNetworkImageProvider. – JRamos29 Jun 05 '20 at 14:13

1 Answers1

6

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...

pskink
  • 23,874
  • 6
  • 66
  • 77