image_provider.dart 25.2 KB
Newer Older
1 2 3 4 5
// Copyright 2015 The Chromium Authors. All rights reserved.
// 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 instantiateImageCodec, Codec;
Ian Hickson's avatar
Ian Hickson committed
9
import 'dart:ui' show Size, Locale, TextDirection, hashValues;
10 11

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

14
import 'binding.dart';
15
import 'image_cache.dart';
16 17 18 19
import 'image_stream.dart';

/// Configuration information passed to the [ImageProvider.resolve] method to
/// select a specific image.
20 21 22 23 24 25 26
///
/// 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.
27
@immutable
28 29 30 31 32 33 34 35 36
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
37
    this.textDirection,
38
    this.size,
Ian Hickson's avatar
Ian Hickson committed
39
    this.platform,
40 41 42 43 44 45 46 47 48 49
  });

  /// 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({
    AssetBundle bundle,
    double devicePixelRatio,
    Locale locale,
Ian Hickson's avatar
Ian Hickson committed
50
    TextDirection textDirection,
51
    Size size,
Ian Hickson's avatar
Ian Hickson committed
52
    String platform,
53 54 55 56 57
  }) {
    return new ImageConfiguration(
      bundle: bundle ?? this.bundle,
      devicePixelRatio: devicePixelRatio ?? this.devicePixelRatio,
      locale: locale ?? this.locale,
Ian Hickson's avatar
Ian Hickson committed
58
      textDirection: textDirection ?? this.textDirection,
59
      size: size ?? this.size,
Ian Hickson's avatar
Ian Hickson committed
60
      platform: platform ?? this.platform,
61 62 63 64 65 66 67 68 69 70 71 72 73
    );
  }

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

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

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

Ian Hickson's avatar
Ian Hickson committed
74 75 76
  /// The reading direction of the language for which to select the image.
  final TextDirection textDirection;

77 78 79
  /// The size at which the image will be rendered.
  final Size size;

80 81 82 83 84
  /// 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.
  final TargetPlatform platform;
85 86 87 88

  /// An image configuration that provides no additional information.
  ///
  /// Useful when resolving an [ImageProvider] without any context.
89
  static const ImageConfiguration empty = ImageConfiguration();
90 91 92 93 94 95 96 97 98

  @override
  bool operator ==(dynamic other) {
    if (other.runtimeType != runtimeType)
      return false;
    final ImageConfiguration typedOther = other;
    return typedOther.bundle == bundle
        && typedOther.devicePixelRatio == devicePixelRatio
        && typedOther.locale == locale
Ian Hickson's avatar
Ian Hickson committed
99
        && typedOther.textDirection == textDirection
100 101 102 103 104 105 106 107 108
        && typedOther.size == size
        && typedOther.platform == platform;
  }

  @override
  int get hashCode => hashValues(bundle, devicePixelRatio, locale, size, platform);

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

/// 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.
///
160
/// [ImageProvider] uses the global [imageCache] to cache images.
161 162 163
///
/// 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
164 165 166
/// should be immutable and implement the [==] operator and the [hashCode]
/// getter. Subclasses should subclass a variant of [ImageProvider] with an
/// explicit `T` type argument.
167 168 169
///
/// The type argument does not have to be specified when using the type as an
/// argument (where any image provider is acceptable).
170
///
171 172
/// The following image formats are supported: {@macro flutter.dart:ui.imageFormats}
///
173 174 175
/// ## Sample code
///
/// The following shows the code required to write a widget that fully conforms
176
/// to the [ImageProvider] and [Widget] protocols. (It is essentially a
177
/// bare-bones version of the [widgets.Image] widget.)
178 179
///
/// ```dart
180 181
/// class MyImage extends StatefulWidget {
///   const MyImage({
182 183 184 185 186 187 188 189
///     Key key,
///     @required this.imageProvider,
///   }) : assert(imageProvider != null),
///        super(key: key);
///
///   final ImageProvider imageProvider;
///
///   @override
190
///   _MyImageState createState() => new _MyImageState();
191 192
/// }
///
193
/// class _MyImageState extends State<MyImage> {
194 195 196 197 198 199 200 201 202 203 204 205 206
///   ImageStream _imageStream;
///   ImageInfo _imageInfo;
///
///   @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
207
///   void didUpdateWidget(MyImage oldWidget) {
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
///     super.didUpdateWidget(oldWidget);
///     if (widget.imageProvider != oldWidget.imageProvider)
///       _getImage();
///   }
///
///   void _getImage() {
///     final ImageStream oldImageStream = _imageStream;
///     _imageStream = widget.imageProvider.resolve(createLocalImageConfiguration(context));
///     if (_imageStream.key != oldImageStream?.key) {
///       // 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.
///       oldImageStream?.removeListener(_updateImage);
///       _imageStream.addListener(_updateImage);
///     }
///   }
///
///   void _updateImage(ImageInfo imageInfo, bool synchronousCall) {
///     setState(() {
///       // Trigger a build whenever the image changes.
///       _imageInfo = imageInfo;
///     });
///   }
///
///   @override
///   void dispose() {
///     _imageStream.removeListener(_updateImage);
///     super.dispose();
///   }
///
///   @override
///   Widget build(BuildContext context) {
///     return new RawImage(
///       image: _imageInfo?.image, // this is a dart:ui Image object
///       scale: _imageInfo?.scale ?? 1.0,
///     );
///   }
/// }
/// ```
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
@optionalTypeArgs
abstract class ImageProvider<T> {
  /// 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
  /// method.
  ImageStream resolve(ImageConfiguration configuration) {
    assert(configuration != null);
    final ImageStream stream = new ImageStream();
    T obtainedKey;
264
    obtainKey(configuration).then<void>((T key) {
265
      obtainedKey = key;
266
      stream.setCompleter(PaintingBinding.instance.imageCache.putIfAbsent(key, () => load(key)));
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
    }).catchError(
      (dynamic exception, StackTrace stack) async {
        FlutterError.reportError(new FlutterErrorDetails(
          exception: exception,
          stack: stack,
          library: 'services library',
          context: 'while resolving an image',
          silent: true, // could be a network error or whatnot
          informationCollector: (StringBuffer information) {
            information.writeln('Image provider: $this');
            information.writeln('Image configuration: $configuration');
            if (obtainedKey != null)
              information.writeln('Image key: $obtainedKey');
          }
        ));
        return null;
      }
    );
    return stream;
  }

288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
  /// 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].
  ///
  /// ## Sample code
  ///
  /// The following sample code shows how an image loaded using the [Image]
  /// widget can be evicted using a [NetworkImage] with a matching url.
  ///
  /// ```dart
  /// class MyWidget extends StatelessWidget {
  ///   final String url = '...';
  ///
  ///   @override
  ///   Widget build(BuildContext context) {
  ///     return new Image.network(url);
  ///   }
  ///
  ///   void evictImage() {
  ///     final NetworkImage provider = new NetworkImage(url);
  ///     provider.evict().then<void>((bool success) {
  ///       if (success)
  ///         debugPrint('removed image!');
  ///     });
  ///   }
  /// }
  /// ```
  Future<bool> evict({ImageCache cache, ImageConfiguration configuration = ImageConfiguration.empty}) async {
    cache ??= imageCache;
    final T key = await obtainKey(configuration);
    return cache.evict(key);
  }

331 332 333 334 335 336 337 338
  /// 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
339
  /// implements [==]).
340 341 342 343 344 345 346 347 348 349 350 351
  @protected
  Future<T> obtainKey(ImageConfiguration configuration);

  /// Converts a key into an [ImageStreamCompleter], and begins fetching the
  /// image.
  @protected
  ImageStreamCompleter load(T key);

  @override
  String toString() => '$runtimeType()';
}

352
/// Key for the image obtained by an [AssetImage] or [ExactAssetImage].
353
///
354
/// This is used to identify the precise resource in the [imageCache].
355
@immutable
356 357 358 359 360 361 362 363
class AssetBundleImageKey {
  /// Creates the key for an [AssetImage] or [AssetBundleImageProvider].
  ///
  /// The arguments must not be null.
  const AssetBundleImageKey({
    @required this.bundle,
    @required this.name,
    @required this.scale
364 365 366
  }) : assert(bundle != null),
       assert(name != null),
       assert(scale != null);
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394

  /// 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
  bool operator ==(dynamic other) {
    if (other.runtimeType != runtimeType)
      return false;
    final AssetBundleImageKey typedOther = other;
    return bundle == typedOther.bundle
        && name == typedOther.name
        && scale == typedOther.scale;
  }

  @override
  int get hashCode => hashValues(bundle, name, scale);

  @override
395
  String toString() => '$runtimeType(bundle: $bundle, name: "$name", scale: $scale)';
396 397 398
}

/// A subclass of [ImageProvider] that knows about [AssetBundle]s.
399
///
400 401 402
/// 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> {
403 404
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
405
  const AssetBundleImageProvider();
406

407 408
  /// Converts a key into an [ImageStreamCompleter], and begins fetching the
  /// image using [loadAsync].
409
  @override
410
  ImageStreamCompleter load(AssetBundleImageKey key) {
411 412 413
    return new MultiFrameImageStreamCompleter(
      codec: _loadAsync(key),
      scale: key.scale,
414 415 416 417 418
      informationCollector: (StringBuffer information) {
        information.writeln('Image provider: $this');
        information.write('Image key: $key');
      }
    );
419 420
  }

421
  /// Fetches the image from the asset bundle, decodes it, and returns a
422 423 424 425
  /// corresponding [ImageInfo] object.
  ///
  /// This function is used by [load].
  @protected
426
  Future<ui.Codec> _loadAsync(AssetBundleImageKey key) async {
427 428
    final ByteData data = await key.bundle.load(key.name);
    if (data == null)
429
      throw 'Unable to read data';
430
    return await ui.instantiateImageCodec(data.buffer.asUint8List());
431
  }
432 433 434 435
}

/// Fetches the given URL from the network, associating it with the given scale.
///
436
/// The image will be cached regardless of cache headers from the server.
437 438 439 440
///
/// See also:
///
///  * [Image.network] for a shorthand of an [Image] widget backed by [NetworkImage].
441 442 443
// TODO(ianh): Find some way to honour cache headers to the extent that when the
// 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.
444
class NetworkImage extends ImageProvider<NetworkImage> {
445 446 447
  /// Creates an object that fetches the image at the given URL.
  ///
  /// The arguments must not be null.
448
  const NetworkImage(this.url, { this.scale = 1.0 , this.headers })
449 450
      : assert(url != null),
        assert(scale != null);
451 452 453 454 455 456 457

  /// The URL from which the image will be fetched.
  final String url;

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

458 459 460
  /// The HTTP headers that will be used with [HttpClient.get] to fetch image from network.
  final Map<String, String> headers;

461 462 463 464 465 466
  @override
  Future<NetworkImage> obtainKey(ImageConfiguration configuration) {
    return new SynchronousFuture<NetworkImage>(this);
  }

  @override
467
  ImageStreamCompleter load(NetworkImage key) {
468 469 470
    return new MultiFrameImageStreamCompleter(
      codec: _loadAsync(key),
      scale: key.scale,
471 472 473 474 475
      informationCollector: (StringBuffer information) {
        information.writeln('Image provider: $this');
        information.write('Image key: $key');
      }
    );
476 477
  }

478
  static final HttpClient _httpClient = new HttpClient();
479

480
  Future<ui.Codec> _loadAsync(NetworkImage key) async {
481
    assert(key == this);
482 483

    final Uri resolved = Uri.base.resolve(key.url);
484 485 486 487 488
    final HttpClientRequest request = await _httpClient.getUrl(resolved);
    headers?.forEach((String name, String value) {
      request.headers.add(name, value);
    });
    final HttpClientResponse response = await request.close();
489
    if (response.statusCode != HttpStatus.ok)
490
      throw new Exception('HTTP request failed, statusCode: ${response?.statusCode}, $resolved');
491

492
    final Uint8List bytes = await consolidateHttpClientResponseBytes(response);
493
    if (bytes.lengthInBytes == 0)
494
      throw new Exception('NetworkImage is an empty file: $resolved');
495

496
    return await ui.instantiateImageCodec(bytes);
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
  }

  @override
  bool operator ==(dynamic other) {
    if (other.runtimeType != runtimeType)
      return false;
    final NetworkImage typedOther = other;
    return url == typedOther.url
        && scale == typedOther.scale;
  }

  @override
  int get hashCode => hashValues(url, scale);

  @override
  String toString() => '$runtimeType("$url", scale: $scale)';
}

Ian Hickson's avatar
Ian Hickson committed
515 516
/// Decodes the given [File] object as an image, associating it with the given
/// scale.
517 518 519 520
///
/// See also:
///
///  * [Image.file] for a shorthand of an [Image] widget backed by [FileImage].
Ian Hickson's avatar
Ian Hickson committed
521 522 523 524
class FileImage extends ImageProvider<FileImage> {
  /// Creates an object that decodes a [File] as an image.
  ///
  /// The arguments must not be null.
525
  const FileImage(this.file, { this.scale = 1.0 })
526 527
      : assert(file != null),
        assert(scale != null);
Ian Hickson's avatar
Ian Hickson committed
528 529 530 531 532 533 534 535 536 537 538 539 540 541

  /// 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) {
    return new SynchronousFuture<FileImage>(this);
  }

  @override
  ImageStreamCompleter load(FileImage key) {
542 543 544
    return new MultiFrameImageStreamCompleter(
      codec: _loadAsync(key),
      scale: key.scale,
Ian Hickson's avatar
Ian Hickson committed
545 546 547 548 549 550
      informationCollector: (StringBuffer information) {
        information.writeln('Path: ${file?.path}');
      }
    );
  }

551
  Future<ui.Codec> _loadAsync(FileImage key) async {
Ian Hickson's avatar
Ian Hickson committed
552 553
    assert(key == this);

554
    final Uint8List bytes = await file.readAsBytes();
Ian Hickson's avatar
Ian Hickson committed
555 556 557
    if (bytes.lengthInBytes == 0)
      return null;

558
    return await ui.instantiateImageCodec(bytes);
Ian Hickson's avatar
Ian Hickson committed
559 560 561 562 563 564 565
  }

  @override
  bool operator ==(dynamic other) {
    if (other.runtimeType != runtimeType)
      return false;
    final FileImage typedOther = other;
566
    return file?.path == typedOther.file?.path
Ian Hickson's avatar
Ian Hickson committed
567 568 569 570 571 572 573 574 575 576
        && scale == typedOther.scale;
  }

  @override
  int get hashCode => hashValues(file?.path, scale);

  @override
  String toString() => '$runtimeType("${file?.path}", scale: $scale)';
}

577 578
/// Decodes the given [Uint8List] buffer as an image, associating it with the
/// given scale.
579 580 581 582 583 584
///
/// 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.
585 586 587 588
///
/// See also:
///
///  * [Image.memory] for a shorthand of an [Image] widget backed by [MemoryImage].
589 590 591 592
class MemoryImage extends ImageProvider<MemoryImage> {
  /// Creates an object that decodes a [Uint8List] buffer as an image.
  ///
  /// The arguments must not be null.
593
  const MemoryImage(this.bytes, { this.scale = 1.0 })
594 595
      : assert(bytes != null),
        assert(scale != null);
596 597 598 599 600 601 602 603 604 605 606 607 608 609

  /// The bytes to decode into an image.
  final Uint8List bytes;

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

  @override
  Future<MemoryImage> obtainKey(ImageConfiguration configuration) {
    return new SynchronousFuture<MemoryImage>(this);
  }

  @override
  ImageStreamCompleter load(MemoryImage key) {
610 611 612 613
    return new MultiFrameImageStreamCompleter(
      codec: _loadAsync(key),
      scale: key.scale
    );
614 615
  }

616
  Future<ui.Codec> _loadAsync(MemoryImage key) {
617 618
    assert(key == this);

619
    return ui.instantiateImageCodec(bytes);
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
  }

  @override
  bool operator ==(dynamic other) {
    if (other.runtimeType != runtimeType)
      return false;
    final MemoryImage typedOther = other;
    return bytes == typedOther.bytes
        && scale == typedOther.scale;
  }

  @override
  int get hashCode => hashValues(bytes.hashCode, scale);

  @override
635
  String toString() => '$runtimeType(${describeIdentity(bytes)}, scale: $scale)';
636
}
637

638 639
/// Fetches an image from an [AssetBundle], associating it with the given scale.
///
640
/// This implementation requires an explicit final [assetName] and [scale] on
641 642 643 644
/// 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].
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
///
/// ## 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
/// `icons` with an image `heart.png`. First, the [pubspec.yaml] of the project
/// should specify its assets in the `flutter` section:
///
/// ```yaml
/// flutter:
///   assets:
///     - icons/heart.png
/// ```
///
/// Then, to fetch the image and associate it with scale `1.5`, use
///
/// ```dart
/// new AssetImage('icons/heart.png', scale: 1.5)
/// ```
///
///## Assets in packages
///
/// 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:
///
/// ```dart
/// new AssetImage('icons/heart.png', scale: 1.5, package: 'my_icons')
/// ```
///
/// Assets used by the package itself should also be fetched using the [package]
/// argument as above.
///
678
/// If the desired asset is specified in the `pubspec.yaml` of the package, it
679
/// is bundled automatically with the app. In particular, assets used by the
680
/// package itself must be specified in its `pubspec.yaml`.
681 682
///
/// A package can also choose to have assets in its 'lib/' folder that are not
683
/// specified in its `pubspec.yaml`. In this case for those images to be
684 685 686 687 688 689 690 691 692
/// 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
///```
///
693
/// To include, say the first image, the `pubspec.yaml` of the app should specify
694 695 696 697 698 699 700 701 702 703
/// it in the `assets` section:
///
/// ```yaml
///  assets:
///    - packages/fancy_backgrounds/backgrounds/background1.png
/// ```
///
/// Note that the `lib/` is implied, so it should not be included in the asset
/// path.
///
704 705 706 707
/// See also:
///
///  * [Image.asset] for a shorthand of an [Image] widget backed by
///    [ExactAssetImage] when using a scale.
708 709 710
class ExactAssetImage extends AssetBundleImageProvider {
  /// Creates an object that fetches the given image from an asset bundle.
  ///
711
  /// The [assetName] and [scale] arguments must not be null. The [scale] arguments
712 713 714
  /// 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.
715 716 717 718 719
  ///
  /// 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.
  const ExactAssetImage(this.assetName, {
720
    this.scale = 1.0,
721 722 723
    this.bundle,
    this.package,
  }) : assert(assetName != null),
724
       assert(scale != null);
725

726 727 728
  /// The name of the asset.
  final String assetName;

729 730
  /// The key to use to obtain the resource from the [bundle]. This is the
  /// argument passed to [AssetBundle.load].
731
  String get keyName => package == null ? assetName : 'packages/$package/$assetName';
732 733 734 735 736 737 738 739 740 741 742

  /// 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]
743
  /// using the key given by [keyName].
744 745
  final AssetBundle bundle;

746 747 748 749
  /// The name of the package from which the image is included. See the
  /// documentation for the [ExactAssetImage] class itself for details.
  final String package;

750 751 752 753
  @override
  Future<AssetBundleImageKey> obtainKey(ImageConfiguration configuration) {
    return new SynchronousFuture<AssetBundleImageKey>(new AssetBundleImageKey(
      bundle: bundle ?? configuration.bundle ?? rootBundle,
754
      name: keyName,
755 756 757 758 759 760 761 762 763
      scale: scale
    ));
  }

  @override
  bool operator ==(dynamic other) {
    if (other.runtimeType != runtimeType)
      return false;
    final ExactAssetImage typedOther = other;
764
    return keyName == typedOther.keyName
765 766 767 768 769
        && scale == typedOther.scale
        && bundle == typedOther.bundle;
  }

  @override
770
  int get hashCode => hashValues(keyName, scale, bundle);
771 772

  @override
773
  String toString() => '$runtimeType(name: "$keyName", scale: $scale, bundle: $bundle)';
774
}