image_provider.dart 40.1 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
6
import 'dart:io';
7
import 'dart:typed_data';
8
import 'dart:ui' as ui show Codec;
9
import 'dart:ui' show Size, Locale, TextDirection;
10 11

import 'package:flutter/foundation.dart';
12
import 'package:flutter/services.dart';
13

14 15
import '_network_image_io.dart'
  if (dart.library.html) '_network_image_web.dart' as network_image;
16
import 'binding.dart';
17
import 'image_cache.dart';
18 19
import 'image_stream.dart';

Dan Field's avatar
Dan Field committed
20 21 22 23
/// Signature for the callback taken by [_createErrorHandlerAndKey].
typedef _KeyAndErrorHandlerCallback<T> = void Function(T key, ImageErrorListener handleError);

/// Signature used for error handling by [_createErrorHandlerAndKey].
24
typedef _AsyncKeyErrorHandler<T> = Future<void> Function(T key, Object exception, StackTrace? stack);
Dan Field's avatar
Dan Field committed
25

26 27
/// Configuration information passed to the [ImageProvider.resolve] method to
/// select a specific image.
28 29 30 31 32 33 34
///
/// See also:
///
///  * [createLocalImageConfiguration], which creates an [ImageConfiguration]
///    based on ambient configuration in a [Widget] environment.
///  * [ImageProvider], which uses [ImageConfiguration] objects to determine
///    which image to obtain.
35
@immutable
36 37 38 39 40 41 42 43 44
class ImageConfiguration {
  /// Creates an object holding the configuration information for an [ImageProvider].
  ///
  /// All the arguments are optional. Configuration information is merely
  /// advisory and best-effort.
  const ImageConfiguration({
    this.bundle,
    this.devicePixelRatio,
    this.locale,
Ian Hickson's avatar
Ian Hickson committed
45
    this.textDirection,
46
    this.size,
Ian Hickson's avatar
Ian Hickson committed
47
    this.platform,
48 49 50 51 52 53 54
  });

  /// Creates an object holding the configuration information for an [ImageProvider].
  ///
  /// All the arguments are optional. Configuration information is merely
  /// advisory and best-effort.
  ImageConfiguration copyWith({
55 56 57 58 59 60
    AssetBundle? bundle,
    double? devicePixelRatio,
    Locale? locale,
    TextDirection? textDirection,
    Size? size,
    TargetPlatform? platform,
61
  }) {
62
    return ImageConfiguration(
63 64 65
      bundle: bundle ?? this.bundle,
      devicePixelRatio: devicePixelRatio ?? this.devicePixelRatio,
      locale: locale ?? this.locale,
Ian Hickson's avatar
Ian Hickson committed
66
      textDirection: textDirection ?? this.textDirection,
67
      size: size ?? this.size,
Ian Hickson's avatar
Ian Hickson committed
68
      platform: platform ?? this.platform,
69 70 71 72 73
    );
  }

  /// The preferred [AssetBundle] to use if the [ImageProvider] needs one and
  /// does not have one already selected.
74
  final AssetBundle? bundle;
75 76

  /// The device pixel ratio where the image will be shown.
77
  final double? devicePixelRatio;
78 79

  /// The language and region for which to select the image.
80
  final Locale? locale;
81

Ian Hickson's avatar
Ian Hickson committed
82
  /// The reading direction of the language for which to select the image.
83
  final TextDirection? textDirection;
Ian Hickson's avatar
Ian Hickson committed
84

85
  /// The size at which the image will be rendered.
86
  final Size? size;
87

88 89 90 91
  /// The [TargetPlatform] for which assets should be used. This allows images
  /// to be specified in a platform-neutral fashion yet use different assets on
  /// different platforms, to match local conventions e.g. for color matching or
  /// shadows.
92
  final TargetPlatform? platform;
93 94 95 96

  /// An image configuration that provides no additional information.
  ///
  /// Useful when resolving an [ImageProvider] without any context.
97
  static const ImageConfiguration empty = ImageConfiguration();
98 99

  @override
100
  bool operator ==(Object other) {
101 102
    if (other.runtimeType != runtimeType)
      return false;
103 104 105 106 107 108 109
    return other is ImageConfiguration
        && other.bundle == bundle
        && other.devicePixelRatio == devicePixelRatio
        && other.locale == locale
        && other.textDirection == textDirection
        && other.size == size
        && other.platform == platform;
110 111 112
  }

  @override
113
  int get hashCode => Object.hash(bundle, devicePixelRatio, locale, size, platform);
114 115 116

  @override
  String toString() {
117
    final StringBuffer result = StringBuffer();
118 119 120 121
    result.write('ImageConfiguration(');
    bool hasArguments = false;
    if (bundle != null) {
      result.write('bundle: $bundle');
122
      hasArguments = true;
123 124 125 126
    }
    if (devicePixelRatio != null) {
      if (hasArguments)
        result.write(', ');
127
      result.write('devicePixelRatio: ${devicePixelRatio!.toStringAsFixed(1)}');
128
      hasArguments = true;
129 130 131 132 133
    }
    if (locale != null) {
      if (hasArguments)
        result.write(', ');
      result.write('locale: $locale');
134
      hasArguments = true;
135
    }
Ian Hickson's avatar
Ian Hickson committed
136 137 138 139 140 141
    if (textDirection != null) {
      if (hasArguments)
        result.write(', ');
      result.write('textDirection: $textDirection');
      hasArguments = true;
    }
142 143 144 145
    if (size != null) {
      if (hasArguments)
        result.write(', ');
      result.write('size: $size');
146
      hasArguments = true;
147 148 149 150
    }
    if (platform != null) {
      if (hasArguments)
        result.write(', ');
151
      result.write('platform: ${platform!.name}');
152
      hasArguments = true;
153 154 155 156 157 158
    }
    result.write(')');
    return result.toString();
  }
}

159 160
/// Performs the decode process for use in [ImageProvider.load].
///
161 162 163
/// This callback allows decoupling of the `cacheWidth`, `cacheHeight`, and
/// `allowUpscaling` parameters from implementations of [ImageProvider] that do
/// not expose them.
164 165 166
///
/// See also:
///
167 168
///  * [ResizeImage], which uses this to override the `cacheWidth`,
///    `cacheHeight`, and `allowUpscaling` parameters.
169
typedef DecoderCallback = Future<ui.Codec> Function(Uint8List bytes, {int? cacheWidth, int? cacheHeight, bool allowUpscaling});
170

171 172 173 174 175 176 177
/// Identifies an image without committing to the precise final asset. This
/// allows a set of images to be identified and for the precise image to later
/// be resolved based on the environment, e.g. the device pixel ratio.
///
/// To obtain an [ImageStream] from an [ImageProvider], call [resolve],
/// passing it an [ImageConfiguration] object.
///
178
/// [ImageProvider] uses the global [imageCache] to cache images.
179 180 181
///
/// The type argument `T` is the type of the object used to represent a resolved
/// configuration. This is also the type used for the key in the image cache. It
Ian Hickson's avatar
Ian Hickson committed
182 183 184
/// should be immutable and implement the [==] operator and the [hashCode]
/// getter. Subclasses should subclass a variant of [ImageProvider] with an
/// explicit `T` type argument.
185 186 187
///
/// The type argument does not have to be specified when using the type as an
/// argument (where any image provider is acceptable).
188
///
189
/// The following image formats are supported: {@macro dart.ui.imageFormats}
190
///
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
/// ## Lifecycle of resolving an image
///
/// The [ImageProvider] goes through the following lifecycle to resolve an
/// image, once the [resolve] method is called:
///
///   1. Create an [ImageStream] using [createStream] to return to the caller.
///      This stream will be used to communicate back to the caller when the
///      image is decoded and ready to display, or when an error occurs.
///   2. Obtain the key for the image using [obtainKey].
///      Calling this method can throw exceptions into the zone asynchronously
///      or into the callstack synchronously. To handle that, an error handler
///      is created that catches both synchronous and asynchronous errors, to
///      make sure errors can be routed to the correct consumers.
///      The error handler is passed on to [resolveStreamForKey] and the
///      [ImageCache].
///   3. If the key is successfully obtained, schedule resolution of the image
///      using that key. This is handled by [resolveStreamForKey]. That method
///      may fizzle if it determines the image is no longer necessary, use the
///      provided [ImageErrorListener] to report an error, set the completer
///      from the cache if possible, or call [load] to fetch the encoded image
///      bytes and schedule decoding.
///   4. The [load] method is responsible for both fetching the encoded bytes
///      and decoding them using the provided [DecoderCallback]. It is called
///      in a context that uses the [ImageErrorListener] to report errors back.
///
/// Subclasses normally only have to implement the [load] and [obtainKey]
/// methods. A subclass that needs finer grained control over the [ImageStream]
/// type must override [createStream]. A subclass that needs finer grained
/// control over the resolution, such as delaying calling [load], must override
/// [resolveStreamForKey].
///
/// The [resolve] method is marked as [nonVirtual] so that [ImageProvider]s can
/// be properly composed, and so that the base class can properly set up error
/// handling for subsequent methods.
///
/// ## Using an [ImageProvider]
///
228
/// {@tool snippet}
229 230
///
/// The following shows the code required to write a widget that fully conforms
231
/// to the [ImageProvider] and [Widget] protocols. (It is essentially a
232
/// bare-bones version of the [widgets.Image] widget.)
233 234
///
/// ```dart
235 236
/// class MyImage extends StatefulWidget {
///   const MyImage({
237 238 239
///     Key? key,
///     required this.imageProvider,
///   }) : super(key: key);
240 241 242 243
///
///   final ImageProvider imageProvider;
///
///   @override
244
///   State<MyImage> createState() => _MyImageState();
245 246
/// }
///
247
/// class _MyImageState extends State<MyImage> {
248 249
///   ImageStream? _imageStream;
///   ImageInfo? _imageInfo;
250 251 252 253 254 255 256 257 258 259 260
///
///   @override
///   void didChangeDependencies() {
///     super.didChangeDependencies();
///     // We call _getImage here because createLocalImageConfiguration() needs to
///     // be called again if the dependencies changed, in case the changes relate
///     // to the DefaultAssetBundle, MediaQuery, etc, which that method uses.
///     _getImage();
///   }
///
///   @override
261
///   void didUpdateWidget(MyImage oldWidget) {
262
///     super.didUpdateWidget(oldWidget);
263
///     if (widget.imageProvider != oldWidget.imageProvider) {
264
///       _getImage();
265
///     }
266 267 268
///   }
///
///   void _getImage() {
269
///     final ImageStream? oldImageStream = _imageStream;
270
///     _imageStream = widget.imageProvider.resolve(createLocalImageConfiguration(context));
271
///     if (_imageStream!.key != oldImageStream?.key) {
272 273 274
///       // If the keys are the same, then we got the same image back, and so we don't
///       // need to update the listeners. If the key changed, though, we must make sure
///       // to switch our listeners to the new image stream.
275 276
///       final ImageStreamListener listener = ImageStreamListener(_updateImage);
///       oldImageStream?.removeListener(listener);
277
///       _imageStream!.addListener(listener);
278 279 280 281 282 283
///     }
///   }
///
///   void _updateImage(ImageInfo imageInfo, bool synchronousCall) {
///     setState(() {
///       // Trigger a build whenever the image changes.
284
///       _imageInfo?.dispose();
285 286 287 288 289 290
///       _imageInfo = imageInfo;
///     });
///   }
///
///   @override
///   void dispose() {
291
///     _imageStream?.removeListener(ImageStreamListener(_updateImage));
292 293
///     _imageInfo?.dispose();
///     _imageInfo = null;
294 295 296 297 298
///     super.dispose();
///   }
///
///   @override
///   Widget build(BuildContext context) {
299
///     return RawImage(
300 301 302 303 304 305
///       image: _imageInfo?.image, // this is a dart:ui Image object
///       scale: _imageInfo?.scale ?? 1.0,
///     );
///   }
/// }
/// ```
306
/// {@end-tool}
307
@optionalTypeArgs
308
abstract class ImageProvider<T extends Object> {
309 310 311 312 313 314 315 316 317 318
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
  const ImageProvider();

  /// Resolves this image provider using the given `configuration`, returning
  /// an [ImageStream].
  ///
  /// This is the public entry-point of the [ImageProvider] class hierarchy.
  ///
  /// Subclasses should implement [obtainKey] and [load], which are used by this
319 320 321 322 323 324
  /// method. If they need to change the implementation of [ImageStream] used,
  /// they should override [createStream]. If they need to manage the actual
  /// resolution of the image, they should override [resolveStreamForKey].
  ///
  /// See the Lifecycle documentation on [ImageProvider] for more information.
  @nonVirtual
325 326
  ImageStream resolve(ImageConfiguration configuration) {
    assert(configuration != null);
327 328 329
    final ImageStream stream = createStream(configuration);
    // Load the key (potentially asynchronously), set up an error handling zone,
    // and call resolveStreamForKey.
Dan Field's avatar
Dan Field committed
330 331 332 333 334
    _createErrorHandlerAndKey(
      configuration,
      (T key, ImageErrorListener errorHandler) {
        resolveStreamForKey(configuration, stream, key, errorHandler);
      },
335
      (T? key, Object exception, StackTrace? stack) async {
Dan Field's avatar
Dan Field committed
336
        await null; // wait an event turn in case a listener has been added to the image stream.
337
        InformationCollector? collector;
338
        assert(() {
339 340 341 342 343
          collector = () => <DiagnosticsNode>[
            DiagnosticsProperty<ImageProvider>('Image provider', this),
            DiagnosticsProperty<ImageConfiguration>('Image configuration', configuration),
            DiagnosticsProperty<T>('Image key', key, defaultValue: null),
          ];
344 345
          return true;
        }());
346 347 348 349
        if (stream.completer == null) {
          stream.setCompleter(_ErrorImageCompleter());
        }
        stream.completer!.reportError(
Dan Field's avatar
Dan Field committed
350 351 352 353
          exception: exception,
          stack: stack,
          context: ErrorDescription('while resolving an image'),
          silent: true, // could be a network error or whatnot
354 355 356 357
          informationCollector: collector,
        );
      },
    );
358 359 360 361 362 363 364 365 366 367 368 369 370
    return stream;
  }

  /// Called by [resolve] to create the [ImageStream] it returns.
  ///
  /// Subclasses should override this instead of [resolve] if they need to
  /// return some subclass of [ImageStream]. The stream created here will be
  /// passed to [resolveStreamForKey].
  @protected
  ImageStream createStream(ImageConfiguration configuration) {
    return ImageStream();
  }

Dan Field's avatar
Dan Field committed
371 372 373 374 375 376 377 378 379 380
  /// Returns the cache location for the key that this [ImageProvider] creates.
  ///
  /// The location may be [ImageCacheStatus.untracked], indicating that this
  /// image provider's key is not available in the [ImageCache].
  ///
  /// The `cache` and `configuration` parameters must not be null. If the
  /// `handleError` parameter is null, errors will be reported to
  /// [FlutterError.onError], and the method will return null.
  ///
  /// A completed return value of null indicates that an error has occurred.
381
  Future<ImageCacheStatus?> obtainCacheStatus({
382 383
    required ImageConfiguration configuration,
    ImageErrorListener? handleError,
Dan Field's avatar
Dan Field committed
384
  }) {
385
    assert(configuration != null);
386
    final Completer<ImageCacheStatus?> completer = Completer<ImageCacheStatus?>();
Dan Field's avatar
Dan Field committed
387 388 389
    _createErrorHandlerAndKey(
      configuration,
      (T key, ImageErrorListener innerHandleError) {
390
        completer.complete(PaintingBinding.instance.imageCache.statusForKey(key));
Dan Field's avatar
Dan Field committed
391
      },
392
      (T? key, Object exception, StackTrace? stack) async {
Dan Field's avatar
Dan Field committed
393 394 395
        if (handleError != null) {
          handleError(exception, stack);
        } else {
396
          InformationCollector? collector;
397
          assert(() {
398 399 400 401 402
            collector = () => <DiagnosticsNode>[
              DiagnosticsProperty<ImageProvider>('Image provider', this),
              DiagnosticsProperty<ImageConfiguration>('Image configuration', configuration),
              DiagnosticsProperty<T>('Image key', key, defaultValue: null),
            ];
403 404
            return true;
          }());
405 406 407 408 409 410
          FlutterError.reportError(FlutterErrorDetails(
            context: ErrorDescription('while checking the cache location of an image'),
            informationCollector: collector,
            exception: exception,
            stack: stack,
          ));
Dan Field's avatar
Dan Field committed
411 412 413 414 415 416 417 418 419 420 421 422 423
          completer.complete(null);
        }
      },
    );
    return completer.future;
  }

  /// This method is used by both [resolve] and [obtainCacheStatus] to ensure
  /// that errors thrown during key creation are handled whether synchronous or
  /// asynchronous.
  void _createErrorHandlerAndKey(
    ImageConfiguration configuration,
    _KeyAndErrorHandlerCallback<T> successCallback,
424
    _AsyncKeyErrorHandler<T?> errorCallback,
Dan Field's avatar
Dan Field committed
425
  ) {
426
    T? obtainedKey;
427
    bool didError = false;
428
    Future<void> handleError(Object exception, StackTrace? stack) async {
429 430 431
      if (didError) {
        return;
      }
Dan Field's avatar
Dan Field committed
432 433 434
      if (!didError) {
        errorCallback(obtainedKey, exception, stack);
      }
435
      didError = true;
436
    }
437

438 439 440 441 442 443 444 445 446
    Future<T> key;
    try {
      key = obtainKey(configuration);
    } catch (error, stackTrace) {
      handleError(error, stackTrace);
      return;
    }
    key.then<void>((T key) {
      obtainedKey = key;
447
      try {
448
        successCallback(key, handleError);
449 450
      } catch (error, stackTrace) {
        handleError(error, stackTrace);
451
      }
452
    }).catchError(handleError);
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
  }

  /// Called by [resolve] with the key returned by [obtainKey].
  ///
  /// Subclasses should override this method rather than calling [obtainKey] if
  /// they need to use a key directly. The [resolve] method installs appropriate
  /// error handling guards so that errors will bubble up to the right places in
  /// the framework, and passes those guards along to this method via the
  /// [handleError] parameter.
  ///
  /// It is safe for the implementation of this method to call [handleError]
  /// multiple times if multiple errors occur, or if an error is thrown both
  /// synchronously into the current part of the stack and thrown into the
  /// enclosing [Zone].
  ///
  /// The default implementation uses the key to interact with the [ImageCache],
  /// calling [ImageCache.putIfAbsent] and notifying listeners of the [stream].
  /// Implementers that do not call super are expected to correctly use the
  /// [ImageCache].
  @protected
  void resolveStreamForKey(ImageConfiguration configuration, ImageStream stream, T key, ImageErrorListener handleError) {
474 475 476 477
    // This is an unusual edge case where someone has told us that they found
    // the image we want before getting to this method. We should avoid calling
    // load again, but still update the image cache with LRU information.
    if (stream.completer != null) {
478
      final ImageStreamCompleter? completer = PaintingBinding.instance.imageCache.putIfAbsent(
479
        key,
480
        () => stream.completer!,
481 482 483 484 485
        onError: handleError,
      );
      assert(identical(completer, stream.completer));
      return;
    }
486
    final ImageStreamCompleter? completer = PaintingBinding.instance.imageCache.putIfAbsent(
487
      key,
488
      () => load(key, PaintingBinding.instance.instantiateImageCodec),
489 490 491 492 493
      onError: handleError,
    );
    if (completer != null) {
      stream.setCompleter(completer);
    }
494 495
  }

496 497 498 499 500 501 502 503 504 505 506 507 508 509
  /// Evicts an entry from the image cache.
  ///
  /// Returns a [Future] which indicates whether the value was successfully
  /// removed.
  ///
  /// The [ImageProvider] used does not need to be the same instance that was
  /// passed to an [Image] widget, but it does need to create a key which is
  /// equal to one.
  ///
  /// The [cache] is optional and defaults to the global image cache.
  ///
  /// The [configuration] is optional and defaults to
  /// [ImageConfiguration.empty].
  ///
510
  /// {@tool snippet}
511 512
  ///
  /// The following sample code shows how an image loaded using the [Image]
513
  /// widget can be evicted using a [NetworkImage] with a matching URL.
514 515 516
  ///
  /// ```dart
  /// class MyWidget extends StatelessWidget {
517 518 519 520 521 522
  ///   const MyWidget({
  ///     Key? key,
  ///     this.url = ' ... ',
  ///   }) : super(key: key);
  ///
  ///   final String url;
523 524 525
  ///
  ///   @override
  ///   Widget build(BuildContext context) {
526
  ///     return Image.network(url);
527 528 529
  ///   }
  ///
  ///   void evictImage() {
530
  ///     final NetworkImage provider = NetworkImage(url);
531
  ///     provider.evict().then<void>((bool success) {
532
  ///       if (success) {
533
  ///         debugPrint('removed image!');
534
  ///       }
535 536 537 538
  ///     });
  ///   }
  /// }
  /// ```
539
  /// {@end-tool}
540
  Future<bool> evict({ ImageCache? cache, ImageConfiguration configuration = ImageConfiguration.empty }) async {
541 542
    cache ??= imageCache;
    final T key = await obtainKey(configuration);
543
    return cache.evict(key);
544 545
  }

546 547 548 549 550 551 552 553
  /// Converts an ImageProvider's settings plus an ImageConfiguration to a key
  /// that describes the precise image to load.
  ///
  /// The type of the key is determined by the subclass. It is a value that
  /// unambiguously identifies the image (_including its scale_) that the [load]
  /// method will fetch. Different [ImageProvider]s given the same constructor
  /// arguments and [ImageConfiguration] objects should return keys that are
  /// '==' to each other (possibly by using a class for the key that itself
Ian Hickson's avatar
Ian Hickson committed
554
  /// implements [==]).
555 556 557 558
  Future<T> obtainKey(ImageConfiguration configuration);

  /// Converts a key into an [ImageStreamCompleter], and begins fetching the
  /// image.
559 560 561 562 563 564
  ///
  /// The [decode] callback provides the logic to obtain the codec for the
  /// image.
  ///
  /// See also:
  ///
565
  ///  * [ResizeImage], for modifying the key to account for cache dimensions.
566
  @protected
567
  ImageStreamCompleter load(T key, DecoderCallback decode);
568 569

  @override
570
  String toString() => '${objectRuntimeType(this, 'ImageConfiguration')}()';
571 572
}

573
/// Key for the image obtained by an [AssetImage] or [ExactAssetImage].
574
///
575
/// This is used to identify the precise resource in the [imageCache].
576
@immutable
577 578 579 580 581
class AssetBundleImageKey {
  /// Creates the key for an [AssetImage] or [AssetBundleImageProvider].
  ///
  /// The arguments must not be null.
  const AssetBundleImageKey({
582 583 584
    required this.bundle,
    required this.name,
    required this.scale,
585 586 587
  }) : assert(bundle != null),
       assert(name != null),
       assert(scale != null);
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602

  /// The bundle from which the image will be obtained.
  ///
  /// The image is obtained by calling [AssetBundle.load] on the given [bundle]
  /// using the key given by [name].
  final AssetBundle bundle;

  /// The key to use to obtain the resource from the [bundle]. This is the
  /// argument passed to [AssetBundle.load].
  final String name;

  /// The scale to place in the [ImageInfo] object of the image.
  final double scale;

  @override
603
  bool operator ==(Object other) {
604 605
    if (other.runtimeType != runtimeType)
      return false;
606 607 608 609
    return other is AssetBundleImageKey
        && other.bundle == bundle
        && other.name == name
        && other.scale == scale;
610 611 612
  }

  @override
613
  int get hashCode => Object.hash(bundle, name, scale);
614 615

  @override
616
  String toString() => '${objectRuntimeType(this, 'AssetBundleImageKey')}(bundle: $bundle, name: "$name", scale: $scale)';
617 618 619
}

/// A subclass of [ImageProvider] that knows about [AssetBundle]s.
620
///
621 622 623
/// This factors out the common logic of [AssetBundle]-based [ImageProvider]
/// classes, simplifying what subclasses must implement to just [obtainKey].
abstract class AssetBundleImageProvider extends ImageProvider<AssetBundleImageKey> {
624 625
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
626
  const AssetBundleImageProvider();
627

628
  /// Converts a key into an [ImageStreamCompleter], and begins fetching the
629
  /// image.
630
  @override
631
  ImageStreamCompleter load(AssetBundleImageKey key, DecoderCallback decode) {
632
    InformationCollector? collector;
633
    assert(() {
634 635 636 637
      collector = () => <DiagnosticsNode>[
        DiagnosticsProperty<ImageProvider>('Image provider', this),
        DiagnosticsProperty<AssetBundleImageKey>('Image key', key),
      ];
638 639
      return true;
    }());
640
    return MultiFrameImageStreamCompleter(
641
      codec: _loadAsync(key, decode),
642
      scale: key.scale,
643
      debugLabel: key.name,
644
      informationCollector: collector,
645
    );
646 647
  }

648
  /// Fetches the image from the asset bundle, decodes it, and returns a
649 650 651 652
  /// corresponding [ImageInfo] object.
  ///
  /// This function is used by [load].
  @protected
653
  Future<ui.Codec> _loadAsync(AssetBundleImageKey key, DecoderCallback decode) async {
654
    ByteData? data;
655 656 657 658 659
    // Hot reload/restart could change whether an asset bundle or key in a
    // bundle are available, or if it is a network backed bundle.
    try {
      data = await key.bundle.load(key.name);
    } on FlutterError {
660
      PaintingBinding.instance.imageCache.evict(key);
661 662
      rethrow;
    }
663
    if (data == null) {
664
      PaintingBinding.instance.imageCache.evict(key);
665 666
      throw StateError('Unable to read data');
    }
667
    return decode(data.buffer.asUint8List());
668 669 670
  }
}

671 672 673
/// Key used internally by [ResizeImage].
///
/// This is used to identify the precise resource in the [imageCache].
674
@immutable
675 676 677 678
class ResizeImageKey {
  // Private constructor so nobody from the outside can poison the image cache
  // with this key. It's only accessible to [ResizeImage] internally.
  const ResizeImageKey._(this._providerCacheKey, this._width, this._height);
679

680 681 682
  final Object _providerCacheKey;
  final int? _width;
  final int? _height;
683 684 685 686 687

  @override
  bool operator ==(Object other) {
    if (other.runtimeType != runtimeType)
      return false;
688 689 690 691
    return other is ResizeImageKey
        && other._providerCacheKey == _providerCacheKey
        && other._width == _width
        && other._height == _height;
692 693 694
  }

  @override
695
  int get hashCode => Object.hash(_providerCacheKey, _width, _height);
696 697 698 699 700 701 702 703 704 705
}

/// Instructs Flutter to decode the image at the specified dimensions
/// instead of at its native size.
///
/// This allows finer control of the size of the image in [ImageCache] and is
/// generally used to reduce the memory footprint of [ImageCache].
///
/// The decoded image may still be displayed at sizes other than the
/// cached size provided here.
706
class ResizeImage extends ImageProvider<ResizeImageKey> {
707 708 709 710 711 712 713 714 715
  /// Creates an ImageProvider that decodes the image to the specified size.
  ///
  /// The cached image will be directly decoded and stored at the resolution
  /// defined by `width` and `height`. The image will lose detail and
  /// use less memory if resized to a size smaller than the native size.
  const ResizeImage(
    this.imageProvider, {
    this.width,
    this.height,
716 717 718
    this.allowUpscaling = false,
  }) : assert(width != null || height != null),
       assert(allowUpscaling != null);
719 720 721 722 723

  /// The [ImageProvider] that this class wraps.
  final ImageProvider imageProvider;

  /// The width the image should decode to and cache.
724
  final int? width;
725 726

  /// The height the image should decode to and cache.
727
  final int? height;
728

729 730 731 732 733 734 735 736 737
  /// Whether the [width] and [height] parameters should be clamped to the
  /// intrinsic width and height of the image.
  ///
  /// In general, it is better for memory usage to avoid scaling the image
  /// beyond its intrinsic dimensions when decoding it. If there is a need to
  /// scale an image larger, it is better to apply a scale to the canvas, or
  /// to use an appropriate [Image.fit].
  final bool allowUpscaling;

738 739 740 741 742
  /// Composes the `provider` in a [ResizeImage] only when `cacheWidth` and
  /// `cacheHeight` are not both null.
  ///
  /// When `cacheWidth` and `cacheHeight` are both null, this will return the
  /// `provider` directly.
743
  static ImageProvider<Object> resizeIfNeeded(int? cacheWidth, int? cacheHeight, ImageProvider<Object> provider) {
744 745 746 747 748 749
    if (cacheWidth != null || cacheHeight != null) {
      return ResizeImage(provider, width: cacheWidth, height: cacheHeight);
    }
    return provider;
  }

750
  @override
751
  ImageStreamCompleter load(ResizeImageKey key, DecoderCallback decode) {
752
    Future<ui.Codec> decodeResize(Uint8List bytes, {int? cacheWidth, int? cacheHeight, bool? allowUpscaling}) {
753
      assert(
754 755
        cacheWidth == null && cacheHeight == null && allowUpscaling == null,
        'ResizeImage cannot be composed with another ImageProvider that applies '
756
        'cacheWidth, cacheHeight, or allowUpscaling.',
757
      );
758
      return decode(bytes, cacheWidth: width, cacheHeight: height, allowUpscaling: this.allowUpscaling);
759
    }
760
    final ImageStreamCompleter completer = imageProvider.load(key._providerCacheKey, decodeResize);
761
    if (!kReleaseMode) {
762
      completer.debugLabel = '${completer.debugLabel} - Resized(${key._width}×${key._height})';
763 764
    }
    return completer;
765 766 767
  }

  @override
768 769
  Future<ResizeImageKey> obtainKey(ImageConfiguration configuration) {
    Completer<ResizeImageKey>? completer;
770 771
    // If the imageProvider.obtainKey future is synchronous, then we will be able to fill in result with
    // a value before completer is initialized below.
772
    SynchronousFuture<ResizeImageKey>? result;
773 774 775 776
    imageProvider.obtainKey(configuration).then((Object key) {
      if (completer == null) {
        // This future has completed synchronously (completer was never assigned),
        // so we can directly create the synchronous result to return.
777
        result = SynchronousFuture<ResizeImageKey>(ResizeImageKey._(key, width, height));
778 779
      } else {
        // This future did not synchronously complete.
780
        completer.complete(ResizeImageKey._(key, width, height));
781 782 783
      }
    });
    if (result != null) {
784
      return result!;
785
    }
786
    // If the code reaches here, it means the imageProvider.obtainKey was not
787
    // completed sync, so we initialize the completer for completion later.
788
    completer = Completer<ResizeImageKey>();
789
    return completer.future;
790
  }
791 792 793 794
}

/// Fetches the given URL from the network, associating it with the given scale.
///
795
/// The image will be cached regardless of cache headers from the server.
796
///
797 798
/// When a network image is used on the Web platform, the `cacheWidth` and
/// `cacheHeight` parameters of the [DecoderCallback] are ignored as the Web
799 800 801
/// engine delegates image decoding of network images to the Web, which does
/// not support custom decode sizes.
///
802 803 804
/// See also:
///
///  * [Image.network] for a shorthand of an [Image] widget backed by [NetworkImage].
805
// TODO(ianh): Find some way to honor cache headers to the extent that when the
806 807
// last reference to an image is released, we proactively evict the image from
// our cache if the headers describe the image as having expired at that point.
808
abstract class NetworkImage extends ImageProvider<NetworkImage> {
809 810
  /// Creates an object that fetches the image at the given URL.
  ///
811
  /// The arguments [url] and [scale] must not be null.
812
  const factory NetworkImage(String url, { double scale, Map<String, String>? headers }) = network_image.NetworkImage;
813 814

  /// The URL from which the image will be fetched.
815
  String get url;
816 817

  /// The scale to place in the [ImageInfo] object of the image.
818
  double get scale;
819

820
  /// The HTTP headers that will be used with [HttpClient.get] to fetch image from network.
821 822
  ///
  /// When running flutter on the web, headers are not used.
823
  Map<String, String>? get headers;
824 825

  @override
826
  ImageStreamCompleter load(NetworkImage key, DecoderCallback decode);
827 828
}

Ian Hickson's avatar
Ian Hickson committed
829 830
/// Decodes the given [File] object as an image, associating it with the given
/// scale.
831
///
832 833 834
/// The provider does not monitor the file for changes. If you expect the
/// underlying data to change, you should call the [evict] method.
///
835 836 837
/// See also:
///
///  * [Image.file] for a shorthand of an [Image] widget backed by [FileImage].
838
@immutable
Ian Hickson's avatar
Ian Hickson committed
839 840 841 842
class FileImage extends ImageProvider<FileImage> {
  /// Creates an object that decodes a [File] as an image.
  ///
  /// The arguments must not be null.
843
  const FileImage(this.file, { this.scale = 1.0 })
844 845
    : assert(file != null),
      assert(scale != null);
Ian Hickson's avatar
Ian Hickson committed
846 847 848 849 850 851 852 853 854

  /// The file to decode into an image.
  final File file;

  /// The scale to place in the [ImageInfo] object of the image.
  final double scale;

  @override
  Future<FileImage> obtainKey(ImageConfiguration configuration) {
855
    return SynchronousFuture<FileImage>(this);
Ian Hickson's avatar
Ian Hickson committed
856 857 858
  }

  @override
859
  ImageStreamCompleter load(FileImage key, DecoderCallback decode) {
860
    return MultiFrameImageStreamCompleter(
861
      codec: _loadAsync(key, decode),
862
      scale: key.scale,
863
      debugLabel: key.file.path,
864 865 866
      informationCollector: () => <DiagnosticsNode>[
        ErrorDescription('Path: ${file.path}'),
      ],
Ian Hickson's avatar
Ian Hickson committed
867 868 869
    );
  }

870
  Future<ui.Codec> _loadAsync(FileImage key, DecoderCallback decode) async {
Ian Hickson's avatar
Ian Hickson committed
871 872
    assert(key == this);

873
    final Uint8List bytes = await file.readAsBytes();
874 875 876

    if (bytes.lengthInBytes == 0) {
      // The file may become available later.
877
      PaintingBinding.instance.imageCache.evict(key);
878
      throw StateError('$file is empty and cannot be loaded as an image.');
879
    }
Ian Hickson's avatar
Ian Hickson committed
880

881
    return decode(bytes);
Ian Hickson's avatar
Ian Hickson committed
882 883 884
  }

  @override
885
  bool operator ==(Object other) {
Ian Hickson's avatar
Ian Hickson committed
886 887
    if (other.runtimeType != runtimeType)
      return false;
888
    return other is FileImage
889
        && other.file.path == file.path
890
        && other.scale == scale;
Ian Hickson's avatar
Ian Hickson committed
891 892 893
  }

  @override
894
  int get hashCode => Object.hash(file.path, scale);
Ian Hickson's avatar
Ian Hickson committed
895 896

  @override
897
  String toString() => '${objectRuntimeType(this, 'FileImage')}("${file.path}", scale: $scale)';
Ian Hickson's avatar
Ian Hickson committed
898 899
}

900 901
/// Decodes the given [Uint8List] buffer as an image, associating it with the
/// given scale.
902 903 904 905 906 907
///
/// The provided [bytes] buffer should not be changed after it is provided
/// to a [MemoryImage]. To provide an [ImageStream] that represents an image
/// that changes over time, consider creating a new subclass of [ImageProvider]
/// whose [load] method returns a subclass of [ImageStreamCompleter] that can
/// handle providing multiple images.
908 909 910 911
///
/// See also:
///
///  * [Image.memory] for a shorthand of an [Image] widget backed by [MemoryImage].
912
@immutable
913 914 915 916
class MemoryImage extends ImageProvider<MemoryImage> {
  /// Creates an object that decodes a [Uint8List] buffer as an image.
  ///
  /// The arguments must not be null.
917
  const MemoryImage(this.bytes, { this.scale = 1.0 })
918 919
    : assert(bytes != null),
      assert(scale != null);
920 921

  /// The bytes to decode into an image.
922 923
  ///
  /// The bytes represent encoded image bytes and can be encoded in any of the
924
  /// following supported image formats: {@macro dart.ui.imageFormats}
925 926 927 928
  ///
  /// See also:
  ///
  ///  * [PaintingBinding.instantiateImageCodec]
929 930 931
  final Uint8List bytes;

  /// The scale to place in the [ImageInfo] object of the image.
932 933 934 935 936
  ///
  /// See also:
  ///
  ///  * [ImageInfo.scale], which gives more information on how this scale is
  ///    applied.
937 938 939 940
  final double scale;

  @override
  Future<MemoryImage> obtainKey(ImageConfiguration configuration) {
941
    return SynchronousFuture<MemoryImage>(this);
942 943 944
  }

  @override
945
  ImageStreamCompleter load(MemoryImage key, DecoderCallback decode) {
946
    return MultiFrameImageStreamCompleter(
947
      codec: _loadAsync(key, decode),
948
      scale: key.scale,
949
      debugLabel: 'MemoryImage(${describeIdentity(key.bytes)})',
950
    );
951 952
  }

953
  Future<ui.Codec> _loadAsync(MemoryImage key, DecoderCallback decode) {
954 955
    assert(key == this);

956
    return decode(bytes);
957 958 959
  }

  @override
960
  bool operator ==(Object other) {
961 962
    if (other.runtimeType != runtimeType)
      return false;
963 964 965
    return other is MemoryImage
        && other.bytes == bytes
        && other.scale == scale;
966 967 968
  }

  @override
969
  int get hashCode => Object.hash(bytes.hashCode, scale);
970 971

  @override
972
  String toString() => '${objectRuntimeType(this, 'MemoryImage')}(${describeIdentity(bytes)}, scale: $scale)';
973
}
974

975 976
/// Fetches an image from an [AssetBundle], associating it with the given scale.
///
977
/// This implementation requires an explicit final [assetName] and [scale] on
978 979 980 981
/// construction, and ignores the device pixel ratio and size in the
/// configuration passed into [resolve]. For a resolution-aware variant that
/// uses the configuration to pick an appropriate image based on the device
/// pixel ratio and size, see [AssetImage].
982 983 984 985 986
///
/// ## Fetching assets
///
/// When fetching an image provided by the app itself, use the [assetName]
/// argument to name the asset to choose. For instance, consider a directory
987
/// `icons` with an image `heart.png`. First, the `pubspec.yaml` of the project
988 989 990 991 992 993 994 995
/// should specify its assets in the `flutter` section:
///
/// ```yaml
/// flutter:
///   assets:
///     - icons/heart.png
/// ```
///
996
/// Then, to fetch the image and associate it with scale `1.5`, use:
997
///
998
/// {@tool snippet}
999
/// ```dart
1000
/// const ExactAssetImage('icons/heart.png', scale: 1.5)
1001
/// ```
1002
/// {@end-tool}
1003
///
1004
/// ## Assets in packages
1005 1006 1007 1008 1009
///
/// To fetch an asset from a package, the [package] argument must be provided.
/// For instance, suppose the structure above is inside a package called
/// `my_icons`. Then to fetch the image, use:
///
1010
/// {@tool snippet}
1011
/// ```dart
1012
/// const ExactAssetImage('icons/heart.png', scale: 1.5, package: 'my_icons')
1013
/// ```
1014
/// {@end-tool}
1015 1016 1017 1018
///
/// Assets used by the package itself should also be fetched using the [package]
/// argument as above.
///
1019
/// If the desired asset is specified in the `pubspec.yaml` of the package, it
1020
/// is bundled automatically with the app. In particular, assets used by the
1021
/// package itself must be specified in its `pubspec.yaml`.
1022 1023
///
/// A package can also choose to have assets in its 'lib/' folder that are not
1024
/// specified in its `pubspec.yaml`. In this case for those images to be
1025 1026 1027 1028 1029 1030 1031
/// bundled, the app has to specify which ones to include. For instance a
/// package named `fancy_backgrounds` could have:
///
/// ```
/// lib/backgrounds/background1.png
/// lib/backgrounds/background2.png
/// lib/backgrounds/background3.png
1032
/// ```
1033
///
1034
/// To include, say the first image, the `pubspec.yaml` of the app should specify
1035 1036 1037
/// it in the `assets` section:
///
/// ```yaml
1038 1039
///   assets:
///     - packages/fancy_backgrounds/backgrounds/background1.png
1040 1041
/// ```
///
Ian Hickson's avatar
Ian Hickson committed
1042
/// The `lib/` is implied, so it should not be included in the asset path.
1043
///
1044 1045 1046 1047
/// See also:
///
///  * [Image.asset] for a shorthand of an [Image] widget backed by
///    [ExactAssetImage] when using a scale.
1048
@immutable
1049 1050 1051
class ExactAssetImage extends AssetBundleImageProvider {
  /// Creates an object that fetches the given image from an asset bundle.
  ///
1052
  /// The [assetName] and [scale] arguments must not be null. The [scale] arguments
1053 1054 1055
  /// defaults to 1.0. The [bundle] argument may be null, in which case the
  /// bundle provided in the [ImageConfiguration] passed to the [resolve] call
  /// will be used instead.
1056 1057 1058 1059
  ///
  /// The [package] argument must be non-null when fetching an asset that is
  /// included in a package. See the documentation for the [ExactAssetImage] class
  /// itself for details.
1060 1061
  const ExactAssetImage(
    this.assetName, {
1062
    this.scale = 1.0,
1063 1064 1065
    this.bundle,
    this.package,
  }) : assert(assetName != null),
1066
       assert(scale != null);
1067

1068 1069 1070
  /// The name of the asset.
  final String assetName;

1071 1072
  /// The key to use to obtain the resource from the [bundle]. This is the
  /// argument passed to [AssetBundle.load].
1073
  String get keyName => package == null ? assetName : 'packages/$package/$assetName';
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084

  /// The scale to place in the [ImageInfo] object of the image.
  final double scale;

  /// The bundle from which the image will be obtained.
  ///
  /// If the provided [bundle] is null, the bundle provided in the
  /// [ImageConfiguration] passed to the [resolve] call will be used instead. If
  /// that is also null, the [rootBundle] is used.
  ///
  /// The image is obtained by calling [AssetBundle.load] on the given [bundle]
1085
  /// using the key given by [keyName].
1086
  final AssetBundle? bundle;
1087

1088 1089
  /// The name of the package from which the image is included. See the
  /// documentation for the [ExactAssetImage] class itself for details.
1090
  final String? package;
1091

1092 1093
  @override
  Future<AssetBundleImageKey> obtainKey(ImageConfiguration configuration) {
1094
    return SynchronousFuture<AssetBundleImageKey>(AssetBundleImageKey(
1095
      bundle: bundle ?? configuration.bundle ?? rootBundle,
1096
      name: keyName,
1097
      scale: scale,
1098 1099 1100 1101
    ));
  }

  @override
1102
  bool operator ==(Object other) {
1103 1104
    if (other.runtimeType != runtimeType)
      return false;
1105 1106 1107 1108
    return other is ExactAssetImage
        && other.keyName == keyName
        && other.scale == scale
        && other.bundle == bundle;
1109 1110 1111
  }

  @override
1112
  int get hashCode => Object.hash(keyName, scale, bundle);
1113 1114

  @override
1115
  String toString() => '${objectRuntimeType(this, 'ExactAssetImage')}(name: "$keyName", scale: $scale, bundle: $bundle)';
1116
}
1117 1118

// A completer used when resolving an image fails sync.
1119
class _ErrorImageCompleter extends ImageStreamCompleter { }
1120 1121 1122

/// The exception thrown when the HTTP request to load a network image fails.
class NetworkImageLoadException implements Exception {
1123 1124
  /// Creates a [NetworkImageLoadException] with the specified http [statusCode]
  /// and [uri].
1125
  NetworkImageLoadException({required this.statusCode, required this.uri})
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
      : assert(uri != null),
        assert(statusCode != null),
        _message = 'HTTP request failed, statusCode: $statusCode, $uri';

  /// The HTTP status code from the server.
  final int statusCode;

  /// A human-readable error message.
  final String _message;

1136
  /// Resolved URL of the requested image.
1137 1138 1139 1140 1141
  final Uri uri;

  @override
  String toString() => _message;
}