한경완
한경완

Reputation: 35

Flutter CachedNetworkImage Continuously Reloads Previously Loaded Images

I'm using the CachedNetworkImage widget in Flutter to load images from Firebase Storage download links. Despite the images being cached, I notice a delay in image loading every time a page transitions, as if the images are being reloaded from scratch. This significantly affects the user experience, as there is a noticeable lag even for previously loaded (cached) images.

example video

I want these images to display instantly without any delay.

Here's the function I'm using to return the widget:

class CustomCacheManager {
  static const key = 'imageCache';

  static CacheManager instance = CacheManager(
    Config(
      key,
      stalePeriod: const Duration(days: 1),
      maxNrOfCacheObjects: 100, // 최대 캐시 객체 수를 100개로 제한
      repo: JsonCacheInfoRepository(databaseName: key),
      fileService: HttpFileService(),
    ),
  );
}

Widget getImage(String imageUrl) {
  try {
    if (imageUrl == '') {
      return const SizedBox.shrink();
    } else {
      return Container(
          decoration: BoxDecoration(
              border: Border.all(color: Colors.black, width: 2.0),
              borderRadius: BorderRadius.circular(10.0)),
          child: ClipRRect(
              borderRadius: BorderRadius.circular(8.0),
              child: CachedNetworkImage(
                imageUrl: imageUrl,
                cacheManager: CustomCacheManager.instance,
                placeholder: (context, url) => const SkeletonItem(
                    child: SizedBox.shrink()),
                errorWidget: (context, url, error) => const Icon(Icons.error),
                fit: BoxFit.fill,
              )));
    }
  } catch (e) {
    return const SizedBox.shrink();
  }
}

Can anyone explain why this happens and suggest any solutions to ensure images load instantly from the cache upon navigating between pages?

Upvotes: 1

Views: 785

Answers (2)

Thomaswomas
Thomaswomas

Reputation: 11

If the images reload every time a new page shows, they are most likely too big for the memory you allow your app. If you increase the memory imageCache like this, they will most likely not refresh anymore:

PaintingBinding.instance.imageCache.maximumSizeBytes = 200 << 20;

Upvotes: 1

Dhafin Rayhan
Dhafin Rayhan

Reputation: 8499

While the image is being cached, the internal OctoImage widget still need some time to load the image from the cache. Best you can do to minimize the fade duration is to set fadeInDuration to Duration.zero.

CachedNetworkImage(
  fadeInDuration: Duration.zero,
  // ...
)

Note: cached_network_image uses octo_image to render image widgets.

Upvotes: 1

Related Questions