precacheImage function

Future<void> precacheImage (ImageProvider provider, BuildContext context, { Size size, 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 precaching.

See also:

  • ImageCache, which holds images that may be reused.

Implementation

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);
  void listener(ImageInfo image, bool sync) {
    completer.complete();
  }
  void errorListener(dynamic exception, StackTrace stackTrace) {
    completer.complete();
    if (onError != null) {
      onError(exception, stackTrace);
    } else {
      FlutterError.reportError(FlutterErrorDetails(
        context: 'image failed to precache',
        library: 'image resource service',
        exception: exception,
        stack: stackTrace,
        silent: true,
      ));
    }
  }
  stream.addListener(listener, onError: errorListener);
  completer.future.then<void>((void value) { stream.removeListener(listener); });
  return completer.future;
}