1

I am displaying a list of images inside a GridView in my Flutter app using Image.network(url).

The issue: when scrolling through the grid, NetworkImage seems to open a new TCP connection for each image request instead of reusing an existing one. This causes high network usage and puts a heavy load on the phone.

My code:

`GridView.builder(
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
  crossAxisCount: 3,
  ),
  itemCount: imageUrls.length,
  itemBuilder: (context, index) {
    return Image.network(imageUrls[index]);
  },
);
`

Flutter would reuse existing TCP connections for multiple images from the same domain.

Once an image is downloaded, it would be retrieved from cache (memory or disk) instead of opening a new network connection.

1

2 Answers 2

0

One of the most common and efficient ways is to use the cached_network_image package.

Sign up to request clarification or add additional context in comments.

Comments

0

Cause:

Assuming HTTP/1.1 keep-alive isn’t being re-used, the Image.network will call it's internal HttpClient on every single instance (resulting in imageUrls.length amount of TCP connections being made.

Solution:

cached_network_image also uses the same HttpClient BUT by utilizing the flutter_cache_manager package the same HttpClient is used for different images. So, while caching images this package also fixes the problem where Image.network uses many TCP connections. It also fixes the issue of creating a HttpClient on every request.

How to implement the solution:

By using a custom cacheManager we can control the cache manager thus control

class MyCacheManager extends CacheManager {
  static const key = "myCache";

  MyCacheManager() : super(Config(key));
}

final myCacheManager = MyCacheManager();

// usage
CachedNetworkImage(
  imageUrl: url,
  cacheManager: myCacheManager,
);

Benchmark:

You can also benchmark the comparison as such:

// Example with Image.network
GridView.builder(
  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
  itemCount: imageUrls.length,
  itemBuilder: (context, index) {
    return Image.network(imageUrls[index]);
  },
);

// Example with CachedNetworkImage
GridView.builder(
  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
  itemCount: imageUrls.length,
  itemBuilder: (context, index) {
    return CachedNetworkImage(imageUrl: imageUrls[index]);
  },
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.