How to cache all local images assets in flutter

is the any possible way to load all the assets by path like assets/images/image1
and initialising image cache in main and while calling it it won’t load

I am looking for flutter web solution.

Never used in web, but I think it would have to download the assets to build the cache, thus, filling the browser cache as well.

But this is all waste of RAM and network… I would get a list of all my assets and their sizes, then calculate the blurhash of each one (https://blurha.sh/, there are Dart packages for those, but they are very slow, so you should calculate it in compile time - use a script or something).

Knowing the size and the blurhash, you don’t ever have to worry about images taking some time to load (even so because Flutter sucks a lot with images… even if the image is in RAM, it will always take some ms to render, making sometimes a gap in the rendering (resulting in a flash, blink)).

does this workaround work for local assets?

Not a workaround.

Yes. It will load the image (it doesn’t matter where it is, so it could be from assets or files) and put it on RAM.

Or, in other words: “it will spend valuable time loading images and wasting RAM storing all of them there, even if they are not needed”.

Ergo, the necessity to optimize image sizes before compilation (using Flutter’s DPI aware image (Assets and images | Flutter) and resing images on build time instead of run time, especially if they are optimized (webp or tinyJPG - they can reduce 40% of more in image size without changing quality))

I like @evaluator118’s response here, and it’s something I’m going to look at doing for my own project. However, for the sake of completeness, here’s how I solved the problem without any optimizations or whatnot. (Disclaimer: I don’t necessarily think this is the best solution… just the one I was playing with.)

class ImagePrecacheService {
  static final ImagePrecacheService _instance = ImagePrecacheService._internal();
  static ImagePrecacheService get I => _instance;

  ImagePrecacheService._internal();

  Future<void> precacheImages() async {
    final WidgetsBinding binding = await WidgetsFlutterBinding.ensureInitialized();
    binding.addPostFrameCallback((_) {
      final Element? context = binding.rootElement;
      if (context != null) {
        for (final String asset in _allAsset) {
          try {
            unawaited(precacheImage(AssetImage(asset), context));
          } catch (e) {
            log(
              "Unable to precache image!\nImage: $asset\n$e",
              name: "ImagePrecacheService",
            );
          }
        }
      }
    });
  }

  static const List<String> _allAssets = [
    // There's probably a better way to get the list of assets, but this is how I did it.
  ];
}

Then, in my main.dart:

  if (kIsWeb) {
    await ImagePrecacheService.I.precacheImages();
  }