precacheImage function

Future<void> precacheImage (
  1. ImageProvider provider,
  2. BuildContext context,
  3. {Size size,
  4. ImageErrorListener onError}

Prefetches an image into the image cache.

Returns a Future that will complete when the first image yielded by the ImageProvider is available or failed to load.

If the image is later used by an Image or BoxDecoration or FadeInImage, it will probably be loaded faster. The consumer of the image does not need to use the same ImageProvider instance. The ImageCache will find the image as long as both images share the same key.

The BuildContext and Size are used to select an image configuration (see createLocalImageConfiguration).

The onError argument can be used to manually handle errors while pre-caching.

See also:

  • ImageCache, which holds images that may be reused.


Future<void> precacheImage(
  ImageProvider provider,
  BuildContext context, {
  Size size,
  ImageErrorListener onError,
}) {
  final ImageConfiguration config = createLocalImageConfiguration(context, size: size);
  final Completer<void> completer = Completer<void>();
  final ImageStream stream = provider.resolve(config);
  ImageStreamListener listener;
  listener = ImageStreamListener(
    (ImageInfo image, bool sync) {
    onError: (dynamic exception, StackTrace stackTrace) {
      if (onError != null) {
        onError(exception, stackTrace);
      } else {
          context: ErrorDescription('image failed to precache'),
          library: 'image resource service',
          exception: exception,
          stack: stackTrace,
          silent: true,
  return completer.future;