Flutter-如何将NetworkImage转换为ui.Image?

时间:2020-06-05 03:34:14

标签: image flutter

我需要将NetworkImage转换为ui.Image。 我尝试通过一些调整使用此question中给定的解决方案,但它不起作用。

有人可以帮助我吗?

 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 个答案:

答案 0 :(得分:3)

首先在您的班级中创建一个字段:

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

然后要获得ui.Image,您只需致电:

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');

当然,您应该添加一些http响应错误处理,但这是基本思想...