image_provider.dart 23.7 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';
Ian Hickson's avatar
Ian Hickson committed
6
import 'dart:io' show File;
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
import 'package:http/http.dart' as http;
14

15
import 'binding.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 89 90 91 92 93 94 95 96 97 98

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

  @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 288 289 290 291 292 293 294 295
    }).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;
  }

  /// 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
296
  /// implements [==]).
297 298 299 300 301 302 303 304 305 306 307 308
  @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()';
}

309
/// Key for the image obtained by an [AssetImage] or [ExactAssetImage].
310
///
311
/// This is used to identify the precise resource in the [imageCache].
312
@immutable
313 314 315 316 317 318 319 320
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
321 322 323
  }) : assert(bundle != null),
       assert(name != null),
       assert(scale != null);
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351

  /// 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
352
  String toString() => '$runtimeType(bundle: $bundle, name: "$name", scale: $scale)';
353 354 355
}

/// A subclass of [ImageProvider] that knows about [AssetBundle]s.
356
///
357 358 359
/// 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> {
360 361
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
362
  const AssetBundleImageProvider();
363

364 365
  /// Converts a key into an [ImageStreamCompleter], and begins fetching the
  /// image using [loadAsync].
366
  @override
367
  ImageStreamCompleter load(AssetBundleImageKey key) {
368 369 370
    return new MultiFrameImageStreamCompleter(
      codec: _loadAsync(key),
      scale: key.scale,
371 372 373 374 375
      informationCollector: (StringBuffer information) {
        information.writeln('Image provider: $this');
        information.write('Image key: $key');
      }
    );
376 377
  }

378
  /// Fetches the image from the asset bundle, decodes it, and returns a
379 380 381 382
  /// corresponding [ImageInfo] object.
  ///
  /// This function is used by [load].
  @protected
383
  Future<ui.Codec> _loadAsync(AssetBundleImageKey key) async {
384 385
    final ByteData data = await key.bundle.load(key.name);
    if (data == null)
386
      throw 'Unable to read data';
387
    return await ui.instantiateImageCodec(data.buffer.asUint8List());
388
  }
389 390 391 392
}

/// Fetches the given URL from the network, associating it with the given scale.
///
393
/// The image will be cached regardless of cache headers from the server.
394 395 396 397
///
/// See also:
///
///  * [Image.network] for a shorthand of an [Image] widget backed by [NetworkImage].
398 399 400
// 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.
401
class NetworkImage extends ImageProvider<NetworkImage> {
402 403 404
  /// Creates an object that fetches the image at the given URL.
  ///
  /// The arguments must not be null.
405
  const NetworkImage(this.url, { this.scale: 1.0 , this.headers })
406 407
      : assert(url != null),
        assert(scale != null);
408 409 410 411 412 413 414

  /// 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;

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

418 419 420 421 422 423
  @override
  Future<NetworkImage> obtainKey(ImageConfiguration configuration) {
    return new SynchronousFuture<NetworkImage>(this);
  }

  @override
424
  ImageStreamCompleter load(NetworkImage key) {
425 426 427
    return new MultiFrameImageStreamCompleter(
      codec: _loadAsync(key),
      scale: key.scale,
428 429 430 431 432
      informationCollector: (StringBuffer information) {
        information.writeln('Image provider: $this');
        information.write('Image key: $key');
      }
    );
433 434
  }

435 436
  static final http.Client _httpClient = createHttpClient();

437
  Future<ui.Codec> _loadAsync(NetworkImage key) async {
438
    assert(key == this);
439 440

    final Uri resolved = Uri.base.resolve(key.url);
441
    final http.Response response = await _httpClient.get(resolved, headers: headers);
442
    if (response == null || response.statusCode != 200)
443
      throw new Exception('HTTP request failed, statusCode: ${response?.statusCode}, $resolved');
444

445
    final Uint8List bytes = response.bodyBytes;
446
    if (bytes.lengthInBytes == 0)
447
      throw new Exception('NetworkImage is an empty file: $resolved');
448

449
    return await ui.instantiateImageCodec(bytes);
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
  }

  @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
468 469
/// Decodes the given [File] object as an image, associating it with the given
/// scale.
470 471 472 473
///
/// See also:
///
///  * [Image.file] for a shorthand of an [Image] widget backed by [FileImage].
Ian Hickson's avatar
Ian Hickson committed
474 475 476 477
class FileImage extends ImageProvider<FileImage> {
  /// Creates an object that decodes a [File] as an image.
  ///
  /// The arguments must not be null.
478 479 480
  const FileImage(this.file, { this.scale: 1.0 })
      : assert(file != null),
        assert(scale != null);
Ian Hickson's avatar
Ian Hickson committed
481 482 483 484 485 486 487 488 489 490 491 492 493 494

  /// 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) {
495 496 497
    return new MultiFrameImageStreamCompleter(
      codec: _loadAsync(key),
      scale: key.scale,
Ian Hickson's avatar
Ian Hickson committed
498 499 500 501 502 503
      informationCollector: (StringBuffer information) {
        information.writeln('Path: ${file?.path}');
      }
    );
  }

504
  Future<ui.Codec> _loadAsync(FileImage key) async {
Ian Hickson's avatar
Ian Hickson committed
505 506
    assert(key == this);

507
    final Uint8List bytes = await file.readAsBytes();
Ian Hickson's avatar
Ian Hickson committed
508 509 510
    if (bytes.lengthInBytes == 0)
      return null;

511
    return await ui.instantiateImageCodec(bytes);
Ian Hickson's avatar
Ian Hickson committed
512 513 514 515 516 517 518
  }

  @override
  bool operator ==(dynamic other) {
    if (other.runtimeType != runtimeType)
      return false;
    final FileImage typedOther = other;
519
    return file?.path == typedOther.file?.path
Ian Hickson's avatar
Ian Hickson committed
520 521 522 523 524 525 526 527 528 529
        && scale == typedOther.scale;
  }

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

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

530 531
/// Decodes the given [Uint8List] buffer as an image, associating it with the
/// given scale.
532 533 534 535 536 537
///
/// 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.
538 539 540 541
///
/// See also:
///
///  * [Image.memory] for a shorthand of an [Image] widget backed by [MemoryImage].
542 543 544 545
class MemoryImage extends ImageProvider<MemoryImage> {
  /// Creates an object that decodes a [Uint8List] buffer as an image.
  ///
  /// The arguments must not be null.
546 547 548
  const MemoryImage(this.bytes, { this.scale: 1.0 })
      : assert(bytes != null),
        assert(scale != null);
549 550 551 552 553 554 555 556 557 558 559 560 561 562

  /// 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) {
563 564 565 566
    return new MultiFrameImageStreamCompleter(
      codec: _loadAsync(key),
      scale: key.scale
    );
567 568
  }

569
  Future<ui.Codec> _loadAsync(MemoryImage key) {
570 571
    assert(key == this);

572
    return ui.instantiateImageCodec(bytes);
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
  }

  @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
588
  String toString() => '$runtimeType(${describeIdentity(bytes)}, scale: $scale)';
589
}
590

591 592
/// Fetches an image from an [AssetBundle], associating it with the given scale.
///
593
/// This implementation requires an explicit final [assetName] and [scale] on
594 595 596 597
/// 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].
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
///
/// ## 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.
///
631
/// If the desired asset is specified in the `pubspec.yaml` of the package, it
632
/// is bundled automatically with the app. In particular, assets used by the
633
/// package itself must be specified in its `pubspec.yaml`.
634 635
///
/// A package can also choose to have assets in its 'lib/' folder that are not
636
/// specified in its `pubspec.yaml`. In this case for those images to be
637 638 639 640 641 642 643 644 645
/// 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
///```
///
646
/// To include, say the first image, the `pubspec.yaml` of the app should specify
647 648 649 650 651 652 653 654 655 656
/// 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.
///
657 658 659 660
/// See also:
///
///  * [Image.asset] for a shorthand of an [Image] widget backed by
///    [ExactAssetImage] when using a scale.
661 662 663
class ExactAssetImage extends AssetBundleImageProvider {
  /// Creates an object that fetches the given image from an asset bundle.
  ///
664
  /// The [assetName] and [scale] arguments must not be null. The [scale] arguments
665 666 667
  /// 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.
668 669 670 671 672
  ///
  /// 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, {
673
    this.scale: 1.0,
674 675 676
    this.bundle,
    this.package,
  }) : assert(assetName != null),
677
       assert(scale != null);
678

679 680 681
  /// The name of the asset.
  final String assetName;

682 683
  /// The key to use to obtain the resource from the [bundle]. This is the
  /// argument passed to [AssetBundle.load].
684
  String get keyName => package == null ? assetName : 'packages/$package/$assetName';
685 686 687 688 689 690 691 692 693 694 695

  /// 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]
696
  /// using the key given by [keyName].
697 698
  final AssetBundle bundle;

699 700 701 702
  /// The name of the package from which the image is included. See the
  /// documentation for the [ExactAssetImage] class itself for details.
  final String package;

703 704 705 706
  @override
  Future<AssetBundleImageKey> obtainKey(ImageConfiguration configuration) {
    return new SynchronousFuture<AssetBundleImageKey>(new AssetBundleImageKey(
      bundle: bundle ?? configuration.bundle ?? rootBundle,
707
      name: keyName,
708 709 710 711 712 713 714 715 716
      scale: scale
    ));
  }

  @override
  bool operator ==(dynamic other) {
    if (other.runtimeType != runtimeType)
      return false;
    final ExactAssetImage typedOther = other;
717
    return keyName == typedOther.keyName
718 719 720 721 722
        && scale == typedOther.scale
        && bundle == typedOther.bundle;
  }

  @override
723
  int get hashCode => hashValues(keyName, scale, bundle);
724 725

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