How to combine PrecacheImage with MemoryImage in Flutter

As already stated in many posts precacheImage (and any other Network Image resource loaders, i.e. NetworkImageWithRetry) throws an exception on 404 URL not found error.

To be able to load an image and treat the exception if the resource is not found I build the Image widget with a method that returns a MemoryImage:

static Future<Uint8List> loadBytes(String url, {Map<String, String> headers}) async {
    final Uri resolved = Uri.base.resolve(url);
    final Response response = await _httpClient.get(resolved, headers: headers);
    if (response == null || response.statusCode != 200) throw new Exception('HTTP request failed, statusCode: ${response?.statusCode}, $resolved');

    final Uint8List bytes = response.bodyBytes;
    if (bytes.lengthInBytes == 0) throw new Exception('NetworkImage is an empty file: $resolved');

    return bytes;
  }

  static Future<MemoryImage> loadMemoryImage(String url, {Map<String, String> headers}) async {
    return MemoryImage(await loadBytes(url));
  }

And then in the widget:

loadImage(String url) async {
    try {
      var memImage = await NetworkImageLoader.loadMemoryImage(url);
      setState(() {
        image = Image(image: memImage);
      });
    } catch (e) {
      print('Could not fetch image');
      print(e.toString());
      setState(() {
       image = Icon(Icons.error);
      });
    }
  }

Is there any way to combine those two? To be able to precache an image but feeding it with a MemoryImage.

Leave a Comment