image_provider.dart 27.1 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 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
    return ImageConfiguration(
55 56 57
      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 = 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
/// {@tool sample}
174 175
///
/// 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() => _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
///     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) {
240
///     return RawImage(
241 242 243 244 245 246
///       image: _imageInfo?.image, // this is a dart:ui Image object
///       scale: _imageInfo?.scale ?? 1.0,
///     );
///   }
/// }
/// ```
247
/// {@end-tool}
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
@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);
263
    final ImageStream stream = ImageStream();
264
    T obtainedKey;
265
    bool didError = false;
266
    Future<void> handleError(dynamic exception, StackTrace stack) async {
267 268 269 270
      if (didError) {
        return;
      }
      didError = true;
271 272 273 274 275 276 277 278 279 280 281 282 283 284
      await null; // wait an event turn in case a listener has been added to the image stream.
      final _ErrorImageCompleter imageCompleter = _ErrorImageCompleter();
      stream.setCompleter(imageCompleter);
      imageCompleter.setError(
        exception: exception,
        stack: stack,
        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');
          }
285
        },
286 287
      );
    }
288

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    // If an error is added to a synchronous completer before a listener has been
    // added, it can throw an error both into the zone and up the stack. Thus, it
    // looks like the error has been caught, but it is in fact also bubbling to the
    // zone. Since we cannot prevent all usage of Completer.sync here, or rather
    // that changing them would be too breaking, we instead hook into the same
    // zone mechanism to intercept the uncaught error and deliver it to the
    // image stream's error handler. Note that these errors may be duplicated,
    // hence the need for the `didError` flag.
    final Zone dangerZone = Zone.current.fork(
      specification: ZoneSpecification(
        handleUncaughtError: (Zone zone, ZoneDelegate delegate, Zone parent, Object error, StackTrace stackTrace) {
          handleError(error, stackTrace);
        }
      )
    );
    dangerZone.runGuarded(() {
      Future<T> key;
      try {
        key = obtainKey(configuration);
      } catch (error, stackTrace) {
        handleError(error, stackTrace);
        return;
311
      }
312 313 314 315 316 317 318 319 320
      key.then<void>((T key) {
        obtainedKey = key;
        final ImageStreamCompleter completer = PaintingBinding.instance
            .imageCache.putIfAbsent(key, () => load(key), onError: handleError);
        if (completer != null) {
          stream.setCompleter(completer);
        }
      }).catchError(handleError);
    });
321 322 323
    return stream;
  }

324 325 326 327 328 329 330 331 332 333 334 335 336 337
  /// 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].
  ///
338
  /// {@tool sample}
339 340
  ///
  /// The following sample code shows how an image loaded using the [Image]
341
  /// widget can be evicted using a [NetworkImage] with a matching URL.
342 343 344 345 346 347 348
  ///
  /// ```dart
  /// class MyWidget extends StatelessWidget {
  ///   final String url = '...';
  ///
  ///   @override
  ///   Widget build(BuildContext context) {
349
  ///     return Image.network(url);
350 351 352
  ///   }
  ///
  ///   void evictImage() {
353
  ///     final NetworkImage provider = NetworkImage(url);
354 355 356 357 358 359 360
  ///     provider.evict().then<void>((bool success) {
  ///       if (success)
  ///         debugPrint('removed image!');
  ///     });
  ///   }
  /// }
  /// ```
361
  /// {@end-tool}
362
  Future<bool> evict({ ImageCache cache, ImageConfiguration configuration = ImageConfiguration.empty }) async {
363 364 365 366 367
    cache ??= imageCache;
    final T key = await obtainKey(configuration);
    return cache.evict(key);
  }

368 369 370 371 372 373 374 375
  /// 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
376
  /// implements [==]).
377 378 379 380 381 382 383 384 385 386 387 388
  @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()';
}

389
/// Key for the image obtained by an [AssetImage] or [ExactAssetImage].
390
///
391
/// This is used to identify the precise resource in the [imageCache].
392
@immutable
393 394 395 396 397 398 399
class AssetBundleImageKey {
  /// Creates the key for an [AssetImage] or [AssetBundleImageProvider].
  ///
  /// The arguments must not be null.
  const AssetBundleImageKey({
    @required this.bundle,
    @required this.name,
400
    @required this.scale,
401 402 403
  }) : assert(bundle != null),
       assert(name != null),
       assert(scale != null);
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431

  /// 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
432
  String toString() => '$runtimeType(bundle: $bundle, name: "$name", scale: $scale)';
433 434 435
}

/// A subclass of [ImageProvider] that knows about [AssetBundle]s.
436
///
437 438 439
/// 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> {
440 441
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
442
  const AssetBundleImageProvider();
443

444 445
  /// Converts a key into an [ImageStreamCompleter], and begins fetching the
  /// image using [loadAsync].
446
  @override
447
  ImageStreamCompleter load(AssetBundleImageKey key) {
448
    return MultiFrameImageStreamCompleter(
449 450
      codec: _loadAsync(key),
      scale: key.scale,
451 452 453
      informationCollector: (StringBuffer information) {
        information.writeln('Image provider: $this');
        information.write('Image key: $key');
454
      },
455
    );
456 457
  }

458
  /// Fetches the image from the asset bundle, decodes it, and returns a
459 460 461 462
  /// corresponding [ImageInfo] object.
  ///
  /// This function is used by [load].
  @protected
463
  Future<ui.Codec> _loadAsync(AssetBundleImageKey key) async {
464 465
    final ByteData data = await key.bundle.load(key.name);
    if (data == null)
466
      throw 'Unable to read data';
467
    return await PaintingBinding.instance.instantiateImageCodec(data.buffer.asUint8List());
468
  }
469 470 471 472
}

/// Fetches the given URL from the network, associating it with the given scale.
///
473
/// The image will be cached regardless of cache headers from the server.
474 475 476 477
///
/// See also:
///
///  * [Image.network] for a shorthand of an [Image] widget backed by [NetworkImage].
478 479 480
// 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.
481
class NetworkImage extends ImageProvider<NetworkImage> {
482 483 484
  /// Creates an object that fetches the image at the given URL.
  ///
  /// The arguments must not be null.
485
  const NetworkImage(this.url, { this.scale = 1.0, this.headers })
486 487
    : assert(url != null),
      assert(scale != null);
488 489 490 491 492 493 494

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

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

498 499
  @override
  Future<NetworkImage> obtainKey(ImageConfiguration configuration) {
500
    return SynchronousFuture<NetworkImage>(this);
501 502 503
  }

  @override
504
  ImageStreamCompleter load(NetworkImage key) {
505
    return MultiFrameImageStreamCompleter(
506 507
      codec: _loadAsync(key),
      scale: key.scale,
508 509 510
      informationCollector: (StringBuffer information) {
        information.writeln('Image provider: $this');
        information.write('Image key: $key');
511
      },
512
    );
513 514
  }

515
  static final HttpClient _httpClient = HttpClient();
516

517
  Future<ui.Codec> _loadAsync(NetworkImage key) async {
518
    assert(key == this);
519 520

    final Uri resolved = Uri.base.resolve(key.url);
521 522 523 524 525
    final HttpClientRequest request = await _httpClient.getUrl(resolved);
    headers?.forEach((String name, String value) {
      request.headers.add(name, value);
    });
    final HttpClientResponse response = await request.close();
526
    if (response.statusCode != HttpStatus.ok)
527
      throw Exception('HTTP request failed, statusCode: ${response?.statusCode}, $resolved');
528

529
    final Uint8List bytes = await consolidateHttpClientResponseBytes(response);
530
    if (bytes.lengthInBytes == 0)
531
      throw Exception('NetworkImage is an empty file: $resolved');
532

533
    return PaintingBinding.instance.instantiateImageCodec(bytes);
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
  }

  @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
552 553
/// Decodes the given [File] object as an image, associating it with the given
/// scale.
554 555 556 557
///
/// See also:
///
///  * [Image.file] for a shorthand of an [Image] widget backed by [FileImage].
Ian Hickson's avatar
Ian Hickson committed
558 559 560 561
class FileImage extends ImageProvider<FileImage> {
  /// Creates an object that decodes a [File] as an image.
  ///
  /// The arguments must not be null.
562
  const FileImage(this.file, { this.scale = 1.0 })
563 564
    : assert(file != null),
      assert(scale != null);
Ian Hickson's avatar
Ian Hickson committed
565 566 567 568 569 570 571 572 573

  /// 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) {
574
    return SynchronousFuture<FileImage>(this);
Ian Hickson's avatar
Ian Hickson committed
575 576 577 578
  }

  @override
  ImageStreamCompleter load(FileImage key) {
579
    return MultiFrameImageStreamCompleter(
580 581
      codec: _loadAsync(key),
      scale: key.scale,
Ian Hickson's avatar
Ian Hickson committed
582 583
      informationCollector: (StringBuffer information) {
        information.writeln('Path: ${file?.path}');
584
      },
Ian Hickson's avatar
Ian Hickson committed
585 586 587
    );
  }

588
  Future<ui.Codec> _loadAsync(FileImage key) async {
Ian Hickson's avatar
Ian Hickson committed
589 590
    assert(key == this);

591
    final Uint8List bytes = await file.readAsBytes();
Ian Hickson's avatar
Ian Hickson committed
592 593 594
    if (bytes.lengthInBytes == 0)
      return null;

595
    return await PaintingBinding.instance.instantiateImageCodec(bytes);
Ian Hickson's avatar
Ian Hickson committed
596 597 598 599 600 601 602
  }

  @override
  bool operator ==(dynamic other) {
    if (other.runtimeType != runtimeType)
      return false;
    final FileImage typedOther = other;
603
    return file?.path == typedOther.file?.path
Ian Hickson's avatar
Ian Hickson committed
604 605 606 607 608 609 610 611 612 613
        && scale == typedOther.scale;
  }

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

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

614 615
/// Decodes the given [Uint8List] buffer as an image, associating it with the
/// given scale.
616 617 618 619 620 621
///
/// 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.
622 623 624 625
///
/// See also:
///
///  * [Image.memory] for a shorthand of an [Image] widget backed by [MemoryImage].
626 627 628 629
class MemoryImage extends ImageProvider<MemoryImage> {
  /// Creates an object that decodes a [Uint8List] buffer as an image.
  ///
  /// The arguments must not be null.
630
  const MemoryImage(this.bytes, { this.scale = 1.0 })
631 632
    : assert(bytes != null),
      assert(scale != null);
633 634 635 636 637 638 639 640 641

  /// 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) {
642
    return SynchronousFuture<MemoryImage>(this);
643 644 645 646
  }

  @override
  ImageStreamCompleter load(MemoryImage key) {
647
    return MultiFrameImageStreamCompleter(
648
      codec: _loadAsync(key),
649
      scale: key.scale,
650
    );
651 652
  }

653
  Future<ui.Codec> _loadAsync(MemoryImage key) {
654 655
    assert(key == this);

656
    return PaintingBinding.instance.instantiateImageCodec(bytes);
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
  }

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

675 676
/// Fetches an image from an [AssetBundle], associating it with the given scale.
///
677
/// This implementation requires an explicit final [assetName] and [scale] on
678 679 680 681
/// 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].
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
///
/// ## 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
699
/// AssetImage('icons/heart.png', scale: 1.5)
700 701
/// ```
///
702
/// ## Assets in packages
703 704 705 706 707 708
///
/// 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
709
/// AssetImage('icons/heart.png', scale: 1.5, package: 'my_icons')
710 711 712 713 714
/// ```
///
/// Assets used by the package itself should also be fetched using the [package]
/// argument as above.
///
715
/// If the desired asset is specified in the `pubspec.yaml` of the package, it
716
/// is bundled automatically with the app. In particular, assets used by the
717
/// package itself must be specified in its `pubspec.yaml`.
718 719
///
/// A package can also choose to have assets in its 'lib/' folder that are not
720
/// specified in its `pubspec.yaml`. In this case for those images to be
721 722 723 724 725 726 727
/// 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
728
/// ```
729
///
730
/// To include, say the first image, the `pubspec.yaml` of the app should specify
731 732 733
/// it in the `assets` section:
///
/// ```yaml
734 735
///   assets:
///     - packages/fancy_backgrounds/backgrounds/background1.png
736 737
/// ```
///
Ian Hickson's avatar
Ian Hickson committed
738
/// The `lib/` is implied, so it should not be included in the asset path.
739
///
740 741 742 743
/// See also:
///
///  * [Image.asset] for a shorthand of an [Image] widget backed by
///    [ExactAssetImage] when using a scale.
744 745 746
class ExactAssetImage extends AssetBundleImageProvider {
  /// Creates an object that fetches the given image from an asset bundle.
  ///
747
  /// The [assetName] and [scale] arguments must not be null. The [scale] arguments
748 749 750
  /// 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.
751 752 753 754
  ///
  /// 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.
755 756
  const ExactAssetImage(
    this.assetName, {
757
    this.scale = 1.0,
758 759 760
    this.bundle,
    this.package,
  }) : assert(assetName != null),
761
       assert(scale != null);
762

763 764 765
  /// The name of the asset.
  final String assetName;

766 767
  /// The key to use to obtain the resource from the [bundle]. This is the
  /// argument passed to [AssetBundle.load].
768
  String get keyName => package == null ? assetName : 'packages/$package/$assetName';
769 770 771 772 773 774 775 776 777 778 779

  /// 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]
780
  /// using the key given by [keyName].
781 782
  final AssetBundle bundle;

783 784 785 786
  /// The name of the package from which the image is included. See the
  /// documentation for the [ExactAssetImage] class itself for details.
  final String package;

787 788
  @override
  Future<AssetBundleImageKey> obtainKey(ImageConfiguration configuration) {
789
    return SynchronousFuture<AssetBundleImageKey>(AssetBundleImageKey(
790
      bundle: bundle ?? configuration.bundle ?? rootBundle,
791
      name: keyName,
792
      scale: scale,
793 794 795 796 797 798 799 800
    ));
  }

  @override
  bool operator ==(dynamic other) {
    if (other.runtimeType != runtimeType)
      return false;
    final ExactAssetImage typedOther = other;
801
    return keyName == typedOther.keyName
802 803 804 805 806
        && scale == typedOther.scale
        && bundle == typedOther.bundle;
  }

  @override
807
  int get hashCode => hashValues(keyName, scale, bundle);
808 809

  @override
810
  String toString() => '$runtimeType(name: "$keyName", scale: $scale, bundle: $bundle)';
811
}
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832

// A completer used when resolving an image fails sync.
class _ErrorImageCompleter extends ImageStreamCompleter {
  _ErrorImageCompleter();

  void setError({
    String context,
    dynamic exception,
    StackTrace stack,
    InformationCollector informationCollector,
    bool silent = false,
  }) {
    reportError(
      context: context,
      exception: exception,
      stack: stack,
      informationCollector: informationCollector,
      silent: silent,
    );
  }
}