How set a cache maxHeigth and minWidth on Image.network and dont make a poor quality Image?

Viewed 2595

I have a Flutter app, that is crashing because of images, so I install some plugins to test, after some study, I found a solution for my problem with memory in Flutter. It is setting the cache a Heigth and a Width because the image that comes from the server I did not put a good resize coding and some clients upload large images in dimensions

         Image.network(
                          MainConfig.storageDoc + imageFeature,
                          cacheHeight: constraints.maxHeight.toInt(),
                          cacheWidth: constraints.maxWidth.toInt(),
                          height: constraints.maxHeight,
                          width: constraints.maxWidth,
                          fit: BoxFit.contain,
                        )

the cacheHeight and cacheWith from this save me from memory, now my app is fast but the image is POOR, how can I resize and maintain quality?

3 Answers

I solved the problem and I will post here what is the solution to make a good performance for your app.

After some searches on the web, I found that all the system on the backend that has an upload function for the user upload the image you must make 3 dimensions image.

image-large image-medium image-small

And the following dimensions are respectively 1024, 600 and 300. I use PHP to format all my images and now my app is flying.

This is the helper function that I made and is working great

static String formatImage(String url, [kSize size = kSize.medium]) {
    if (Config().isCacheImage ?? kAdvanceConfig['kIsResizeImage']) {
      String pathWithoutExt = p.withoutExtension(url);
      String ext = p.extension(url);
      String imageURL = url ?? kDefaultImage;

      if (ext == ".jpeg") {
        imageURL = url;
      } else {
        switch (size) {
          case kSize.large:
            imageURL = '$pathWithoutExt-large$ext';
            break;
          case kSize.small:
            imageURL = '$pathWithoutExt-small$ext';
            break;
          default: // kSize.medium:e
            imageURL = '$pathWithoutExt-medium$ext';
            break;
        }
      }

      return imageURL;
    } else {
      return url;
    }
  }

if maxHeight and maxWidth are too small, then the image won't look so good; try to set cacheHeight and cacheWidth to a proper constant value (maybe 700 to 900) and balance it with the memory and keep the fit property to BoxFit.contain; I faced the memory leak problem before and recently was resolved by using the photo_view package in its latest updates, so give it a try;

The type of cacheWidth/Height is int, which is the physical pixel of the image. flutter uses logical pixels, so it needs to be multiplied by devicePixelRatio, like this:

final cacheHeight = (constraints.maxHeight * MediaQuery.of(context).devicePixelRatio).round
Related