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

5 6
// @dart = 2.8

7
import 'dart:async';
8
import 'dart:io' show File;
9
import 'dart:typed_data';
10

11
import 'package:flutter/foundation.dart';
12
import 'package:flutter/painting.dart';
Dan Field's avatar
Dan Field committed
13
import 'package:flutter/scheduler.dart';
14
import 'package:flutter/services.dart';
15
import 'package:flutter/semantics.dart';
16 17

import 'basic.dart';
18
import 'binding.dart';
19
import 'disposable_build_context.dart';
20
import 'framework.dart';
Ian Hickson's avatar
Ian Hickson committed
21
import 'localizations.dart';
22
import 'media_query.dart';
23
import 'scroll_aware_image_provider.dart';
24
import 'ticker_provider.dart';
25

26
export 'package:flutter/painting.dart' show
27 28
  AssetImage,
  ExactAssetImage,
29
  FileImage,
30
  FilterQuality,
31 32 33 34
  ImageConfiguration,
  ImageInfo,
  ImageStream,
  ImageProvider,
35
  MemoryImage,
36
  NetworkImage;
37

38 39 40 41 42
/// Creates an [ImageConfiguration] based on the given [BuildContext] (and
/// optionally size).
///
/// This is the object that must be passed to [BoxPainter.paint] and to
/// [ImageProvider.resolve].
43 44 45
///
/// If this is not called from a build method, then it should be reinvoked
/// whenever the dependencies change, e.g. by calling it from
46
/// [State.didChangeDependencies], so that any changes in the environment are
47 48 49 50 51
/// picked up (e.g. if the device pixel ratio changes).
///
/// See also:
///
///  * [ImageProvider], which has an example showing how this might be used.
52
ImageConfiguration createLocalImageConfiguration(BuildContext context, { Size size }) {
53
  return ImageConfiguration(
54
    bundle: DefaultAssetBundle.of(context),
55
    devicePixelRatio: MediaQuery.of(context, nullOk: true)?.devicePixelRatio ?? 1.0,
Ian Hickson's avatar
Ian Hickson committed
56 57
    locale: Localizations.localeOf(context, nullOk: true),
    textDirection: Directionality.of(context),
58
    size: size,
59
    platform: defaultTargetPlatform,
60 61 62
  );
}

63 64 65
/// Prefetches an image into the image cache.
///
/// Returns a [Future] that will complete when the first image yielded by the
66
/// [ImageProvider] is available or failed to load.
67 68
///
/// If the image is later used by an [Image] or [BoxDecoration] or [FadeInImage],
69 70
/// it will probably be loaded faster. The consumer of the image does not need
/// to use the same [ImageProvider] instance. The [ImageCache] will find the image
Dan Field's avatar
Dan Field committed
71 72 73 74 75 76 77
/// as long as both images share the same key, and the image is held by the
/// cache.
///
/// The cache may refuse to hold the image if it is disabled, the image is too
/// large, or some other criteria implemented by a custom [ImageCache]
/// implementation.
///
78 79 80 81 82 83 84 85 86 87 88
/// The [ImageCache] holds a reference to all images passed to
/// [ImageCache.putIfAbsent] as long as their [ImageStreamCompleter] has at
/// least one listener. This method will wait until the end of the frame after
/// its future completes before releasing its own listener. This gives callers a
/// chance to listen to the stream if necessary. A caller can determine if the
/// image ended up in the cache by calling [ImageProvider.obtainCacheStatus]. If
/// it is only held as [ImageCacheStatus.live], and the caller wishes to keep
/// the resolved image in memory, the caller should immediately call
/// `provider.resolve` and add a listener to the returned [ImageStream]. The
/// image will remain pinned in memory at least until the caller removes its
/// listener from the stream, even if it would not otherwise fit into the cache.
Dan Field's avatar
Dan Field committed
89 90 91
///
/// Callers should be cautious about pinning large images or a large number of
/// images in memory, as this can result in running out of memory and being
92
/// killed by the operating system. The lower the available physical memory, the
Dan Field's avatar
Dan Field committed
93 94
/// more susceptible callers will be to running into OOM issues. These issues
/// manifest as immediate process death, sometimes with no other error messages.
95 96 97 98
///
/// The [BuildContext] and [Size] are used to select an image configuration
/// (see [createLocalImageConfiguration]).
///
99 100
/// The `onError` argument can be used to manually handle errors while
/// pre-caching.
101
///
102 103
/// See also:
///
104
///  * [ImageCache], which holds images that may be reused.
105
Future<void> precacheImage(
106 107 108 109 110
  ImageProvider provider,
  BuildContext context, {
  Size size,
  ImageErrorListener onError,
}) {
111
  final ImageConfiguration config = createLocalImageConfiguration(context, size: size);
112
  final Completer<void> completer = Completer<void>();
113
  final ImageStream stream = provider.resolve(config);
114 115 116
  ImageStreamListener listener;
  listener = ImageStreamListener(
    (ImageInfo image, bool sync) {
117 118 119
      if (!completer.isCompleted) {
        completer.complete();
      }
Dan Field's avatar
Dan Field committed
120 121 122 123 124 125
      // Give callers until at least the end of the frame to subscribe to the
      // image stream.
      // See ImageCache._liveImages
      SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) {
        stream.removeListener(listener);
      });
126 127
    },
    onError: (dynamic exception, StackTrace stackTrace) {
128 129 130
      if (!completer.isCompleted) {
        completer.complete();
      }
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
      stream.removeListener(listener);
      if (onError != null) {
        onError(exception, stackTrace);
      } else {
        FlutterError.reportError(FlutterErrorDetails(
          context: ErrorDescription('image failed to precache'),
          library: 'image resource service',
          exception: exception,
          stack: stackTrace,
          silent: true,
        ));
      }
    },
  );
  stream.addListener(listener);
146 147 148
  return completer.future;
}

149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 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
/// Signature used by [Image.frameBuilder] to control the widget that will be
/// used when an [Image] is built.
///
/// The `child` argument contains the default image widget and is guaranteed to
/// be non-null. Typically, this builder will wrap the `child` widget in some
/// way and return the wrapped widget. If this builder returns `child` directly,
/// it will yield the same result as if [Image.frameBuilder] was null.
///
/// The `frame` argument specifies the index of the current image frame being
/// rendered. It will be null before the first image frame is ready, and zero
/// for the first image frame. For single-frame images, it will never be greater
/// than zero. For multi-frame images (such as animated GIFs), it will increase
/// by one every time a new image frame is shown (including when the image
/// animates in a loop).
///
/// The `wasSynchronouslyLoaded` argument specifies whether the image was
/// available synchronously (on the same
/// [rendering pipeline frame](rendering/RendererBinding/drawFrame.html) as the
/// `Image` widget itself was created) and thus able to be painted immediately.
/// If this is false, then there was one or more rendering pipeline frames where
/// the image wasn't yet available to be painted. For multi-frame images (such
/// as animated GIFs), the value of this argument will be the same for all image
/// frames. In other words, if the first image frame was available immediately,
/// then this argument will be true for all image frames.
///
/// This builder must not return null.
///
/// See also:
///
///  * [Image.frameBuilder], which makes use of this signature in the [Image]
///    widget.
typedef ImageFrameBuilder = Widget Function(
  BuildContext context,
  Widget child,
  int frame,
  bool wasSynchronouslyLoaded,
);

/// Signature used by [Image.loadingBuilder] to build a representation of the
/// image's loading progress.
///
/// This is useful for images that are incrementally loaded (e.g. over a local
/// file system or a network), and the application wishes to give the user an
/// indication of when the image will be displayed.
///
/// The `child` argument contains the default image widget and is guaranteed to
/// be non-null. Typically, this builder will wrap the `child` widget in some
/// way and return the wrapped widget. If this builder returns `child` directly,
/// it will yield the same result as if [Image.loadingBuilder] was null.
///
/// The `loadingProgress` argument contains the current progress towards loading
/// the image. This argument will be non-null while the image is loading, but it
/// will be null in the following cases:
///
///   * When the widget is first rendered before any bytes have been loaded.
///   * When an image has been fully loaded and is available to be painted.
///
/// If callers are implementing custom [ImageProvider] and [ImageStream]
/// instances (which is very rare), it's possible to produce image streams that
/// continue to fire image chunk events after an image frame has been loaded.
/// In such cases, the `child` parameter will represent the current
/// fully-loaded image frame.
///
/// This builder must not return null.
///
/// See also:
///
///  * [Image.loadingBuilder], which makes use of this signature in the [Image]
///    widget.
///  * [ImageChunkListener], a lower-level signature for listening to raw
///    [ImageChunkEvent]s.
typedef ImageLoadingBuilder = Widget Function(
  BuildContext context,
  Widget child,
  ImageChunkEvent loadingProgress,
);

226 227 228 229 230 231 232 233
/// Signature used by [Image.errorBuilder] to create a replacement widget to
/// render instead of the image.
typedef ImageErrorWidgetBuilder = Widget Function(
  BuildContext context,
  Object error,
  StackTrace stackTrace,
);

234 235
/// A widget that displays an image.
///
236 237
/// {@youtube 560 315 https://www.youtube.com/watch?v=7oIAs-0G4mw}
///
238 239 240
/// Several constructors are provided for the various ways that an image can be
/// specified:
///
241 242 243 244 245 246
///  * [new Image], for obtaining an image from an [ImageProvider].
///  * [new Image.asset], for obtaining an image from an [AssetBundle]
///    using a key.
///  * [new Image.network], for obtaining an image from a URL.
///  * [new Image.file], for obtaining an image from a [File].
///  * [new Image.memory], for obtaining an image from a [Uint8List].
247
///
248 249
/// The following image formats are supported: {@macro flutter.dart:ui.imageFormats}
///
250 251 252 253 254 255
/// To automatically perform pixel-density-aware asset resolution, specify the
/// image using an [AssetImage] and make sure that a [MaterialApp], [WidgetsApp],
/// or [MediaQuery] widget exists above the [Image] widget in the widget tree.
///
/// The image is painted using [paintImage], which describes the meanings of the
/// various fields on this class in more detail.
256
///
257
/// {@tool snippet}
258 259 260 261 262 263 264 265 266 267 268 269
/// The default constructor can be used with any [ImageProvider], such as a
/// [NetworkImage], to display an image from the internet.
///
/// ![An image of an owl displayed by the image widget](https://flutter.github.io/assets-for-api-docs/assets/widgets/owl.jpg)
///
/// ```dart
/// const Image(
///   image: NetworkImage('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl.jpg'),
/// )
/// ```
/// {@end-tool}
///
270
/// {@tool snippet}
271 272 273 274 275 276 277 278 279 280 281
/// The [Image] Widget also provides several constructors to display different
/// types of images for convenience. In this example, use the [Image.network]
/// constructor to display an image from the internet.
///
/// ![An image of an owl displayed by the image widget using the shortcut constructor](https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg)
///
/// ```dart
/// Image.network('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg')
/// ```
/// {@end-tool}
///
282 283
/// The [Image.asset], [Image.network], [Image.file], and [Image.memory]
/// constructors allow a custom decode size to be specified through
284
/// `cacheWidth` and `cacheHeight` parameters. The engine will decode the
285 286 287 288
/// image to the specified size, which is primarily intended to reduce the
/// memory usage of [ImageCache].
///
/// In the case where a network image is used on the Web platform, the
289
/// `cacheWidth` and `cacheHeight` parameters are ignored as the Web engine
290 291 292
/// delegates image decoding of network images to the Web, which does not support
/// custom decode sizes.
///
293 294
/// See also:
///
Ian Hickson's avatar
Ian Hickson committed
295 296 297 298
///  * [Icon], which shows an image from a font.
///  * [new Ink.image], which is the preferred way to show an image in a
///    material application (especially if the image is in a [Material] and will
///    have an [InkWell] on top of it).
299
///  * [Image](dart-ui/Image-class.html), the class in the [dart:ui] library.
300 301 302
///  * Cookbook: [Display images from the internet](https://flutter.dev/docs/cookbook/images/network-image)
///  * Cookbook: [Work with cached images](https://flutter.dev/docs/cookbook/images/cached-images)
///  * Cookbook: [Fade in images with a placeholder](https://flutter.dev/docs/cookbook/images/fading-in-images)
303 304 305 306
class Image extends StatefulWidget {
  /// Creates a widget that displays an image.
  ///
  /// To show an image from the network or from an asset bundle, consider using
307
  /// [new Image.network] and [new Image.asset] respectively.
308
  ///
Ian Hickson's avatar
Ian Hickson committed
309 310
  /// The [image], [alignment], [repeat], and [matchTextDirection] arguments
  /// must not be null.
Ian Hickson's avatar
Ian Hickson committed
311 312 313 314 315
  ///
  /// Either the [width] and [height] arguments should be specified, or the
  /// widget should be placed in a context that sets tight layout constraints.
  /// Otherwise, the image dimensions will change as the image is loaded, which
  /// will result in ugly layout changes.
316
  ///
317 318 319 320 321
  /// Use [filterQuality] to change the quality when scaling an image.
  /// Use the [FilterQuality.low] quality setting to scale the image,
  /// which corresponds to bilinear interpolation, rather than the default
  /// [FilterQuality.none] which corresponds to nearest-neighbor.
  ///
322
  /// If [excludeFromSemantics] is true, then [semanticLabel] will be ignored.
323
  const Image({
324 325
    Key key,
    @required this.image,
326 327
    this.frameBuilder,
    this.loadingBuilder,
328
    this.errorBuilder,
329 330
    this.semanticLabel,
    this.excludeFromSemantics = false,
331 332 333
    this.width,
    this.height,
    this.color,
334
    this.colorBlendMode,
335
    this.fit,
336 337
    this.alignment = Alignment.center,
    this.repeat = ImageRepeat.noRepeat,
338
    this.centerSlice,
339 340
    this.matchTextDirection = false,
    this.gaplessPlayback = false,
341
    this.isAntiAlias = false,
342
    this.filterQuality = FilterQuality.low,
343
  }) : assert(image != null),
Ian Hickson's avatar
Ian Hickson committed
344 345
       assert(alignment != null),
       assert(repeat != null),
346
       assert(filterQuality != null),
Ian Hickson's avatar
Ian Hickson committed
347
       assert(matchTextDirection != null),
348
       assert(isAntiAlias != null),
349
       super(key: key);
350 351 352 353

  /// Creates a widget that displays an [ImageStream] obtained from the network.
  ///
  /// The [src], [scale], and [repeat] arguments must not be null.
Ian Hickson's avatar
Ian Hickson committed
354 355 356 357 358
  ///
  /// Either the [width] and [height] arguments should be specified, or the
  /// widget should be placed in a context that sets tight layout constraints.
  /// Otherwise, the image dimensions will change as the image is loaded, which
  /// will result in ugly layout changes.
359 360
  ///
  /// All network images are cached regardless of HTTP headers.
Ian Hickson's avatar
Ian Hickson committed
361 362 363
  ///
  /// An optional [headers] argument can be used to send custom HTTP headers
  /// with the image request.
364
  ///
365 366 367 368 369
  /// Use [filterQuality] to change the quality when scaling an image.
  /// Use the [FilterQuality.low] quality setting to scale the image,
  /// which corresponds to bilinear interpolation, rather than the default
  /// [FilterQuality.none] which corresponds to nearest-neighbor.
  ///
370
  /// If [excludeFromSemantics] is true, then [semanticLabel] will be ignored.
371 372 373 374 375 376 377 378 379 380 381 382 383
  ///
  /// If [cacheWidth] or [cacheHeight] are provided, it indicates to the
  /// engine that the image should be decoded at the specified size. The image
  /// will be rendered to the constraints of the layout or [width] and [height]
  /// regardless of these parameters. These parameters are primarily intended
  /// to reduce the memory usage of [ImageCache].
  ///
  /// In the case where the network image is on the Web platform, the [cacheWidth]
  /// and [cacheHeight] parameters are ignored as the web engine delegates
  /// image decoding to the web which does not support custom decode sizes.
  //
  // TODO(garyq): We should eventually support custom decoding of network images
  // on Web as well, see https://github.com/flutter/flutter/issues/42789.
384 385
  Image.network(
    String src, {
386
    Key key,
387
    double scale = 1.0,
388 389
    this.frameBuilder,
    this.loadingBuilder,
390
    this.errorBuilder,
391 392
    this.semanticLabel,
    this.excludeFromSemantics = false,
393 394 395
    this.width,
    this.height,
    this.color,
396
    this.colorBlendMode,
397
    this.fit,
398 399
    this.alignment = Alignment.center,
    this.repeat = ImageRepeat.noRepeat,
400
    this.centerSlice,
401 402
    this.matchTextDirection = false,
    this.gaplessPlayback = false,
403
    this.filterQuality = FilterQuality.low,
404
    this.isAntiAlias = false,
405
    Map<String, String> headers,
406 407
    int cacheWidth,
    int cacheHeight,
408
  }) : image = ResizeImage.resizeIfNeeded(cacheWidth, cacheHeight, NetworkImage(src, scale: scale, headers: headers)),
Ian Hickson's avatar
Ian Hickson committed
409 410 411
       assert(alignment != null),
       assert(repeat != null),
       assert(matchTextDirection != null),
412 413
       assert(cacheWidth == null || cacheWidth > 0),
       assert(cacheHeight == null || cacheHeight > 0),
414
       assert(isAntiAlias != null),
415 416
       super(key: key);

Ian Hickson's avatar
Ian Hickson committed
417 418 419 420
  /// Creates a widget that displays an [ImageStream] obtained from a [File].
  ///
  /// The [file], [scale], and [repeat] arguments must not be null.
  ///
Ian Hickson's avatar
Ian Hickson committed
421 422 423 424 425
  /// Either the [width] and [height] arguments should be specified, or the
  /// widget should be placed in a context that sets tight layout constraints.
  /// Otherwise, the image dimensions will change as the image is loaded, which
  /// will result in ugly layout changes.
  ///
Ian Hickson's avatar
Ian Hickson committed
426 427
  /// On Android, this may require the
  /// `android.permission.READ_EXTERNAL_STORAGE` permission.
428
  ///
429 430 431 432 433
  /// Use [filterQuality] to change the quality when scaling an image.
  /// Use the [FilterQuality.low] quality setting to scale the image,
  /// which corresponds to bilinear interpolation, rather than the default
  /// [FilterQuality.none] which corresponds to nearest-neighbor.
  ///
434
  /// If [excludeFromSemantics] is true, then [semanticLabel] will be ignored.
435 436 437 438 439 440
  ///
  /// If [cacheWidth] or [cacheHeight] are provided, it indicates to the
  /// engine that the image must be decoded at the specified size. The image
  /// will be rendered to the constraints of the layout or [width] and [height]
  /// regardless of these parameters. These parameters are primarily intended
  /// to reduce the memory usage of [ImageCache].
441 442 443 444 445 446 447 448 449
  ///
  /// Loading an image from a file creates an in memory copy of the file,
  /// which is retained in the [ImageCache]. The underlying file is not
  /// monitored for changes. If it does change, the application should evict
  /// the entry from the [ImageCache].
  ///
  /// See also:
  ///
  ///  * [FileImage] provider for evicting the underlying file easily.
450 451
  Image.file(
    File file, {
Ian Hickson's avatar
Ian Hickson committed
452
    Key key,
453
    double scale = 1.0,
454
    this.frameBuilder,
455
    this.errorBuilder,
456 457
    this.semanticLabel,
    this.excludeFromSemantics = false,
Ian Hickson's avatar
Ian Hickson committed
458 459 460
    this.width,
    this.height,
    this.color,
461
    this.colorBlendMode,
Ian Hickson's avatar
Ian Hickson committed
462
    this.fit,
463 464
    this.alignment = Alignment.center,
    this.repeat = ImageRepeat.noRepeat,
Ian Hickson's avatar
Ian Hickson committed
465
    this.centerSlice,
466 467
    this.matchTextDirection = false,
    this.gaplessPlayback = false,
468
    this.isAntiAlias = false,
469
    this.filterQuality = FilterQuality.low,
470 471
    int cacheWidth,
    int cacheHeight,
472
  }) : image = ResizeImage.resizeIfNeeded(cacheWidth, cacheHeight, FileImage(file, scale: scale)),
473
       loadingBuilder = null,
Ian Hickson's avatar
Ian Hickson committed
474 475
       assert(alignment != null),
       assert(repeat != null),
476
       assert(filterQuality != null),
Ian Hickson's avatar
Ian Hickson committed
477
       assert(matchTextDirection != null),
478 479
       assert(cacheWidth == null || cacheWidth > 0),
       assert(cacheHeight == null || cacheHeight > 0),
480
       assert(isAntiAlias != null),
Ian Hickson's avatar
Ian Hickson committed
481 482
       super(key: key);

483 484 485 486 487 488 489 490 491 492

  // TODO(ianh): Implement the following (see ../services/image_resolution.dart):
  //
  // * If [width] and [height] are both specified, and [scale] is not, then
  //   size-aware asset resolution will be attempted also, with the given
  //   dimensions interpreted as logical pixels.
  //
  // * If the images have platform, locale, or directionality variants, the
  //   current platform, locale, and directionality are taken into account
  //   during asset resolution as well.
493 494 495
  /// Creates a widget that displays an [ImageStream] obtained from an asset
  /// bundle. The key for the image is given by the `name` argument.
  ///
496 497 498 499
  /// The `package` argument must be non-null when displaying an image from a
  /// package and null otherwise. See the `Assets in packages` section for
  /// details.
  ///
500 501 502
  /// If the `bundle` argument is omitted or null, then the
  /// [DefaultAssetBundle] will be used.
  ///
503 504
  /// By default, the pixel-density-aware asset resolution will be attempted. In
  /// addition:
505
  ///
506
  /// * If the `scale` argument is provided and is not null, then the exact
507 508
  /// asset specified will be used. To display an image variant with a specific
  /// density, the exact path must be provided (e.g. `images/2x/cat.png`).
509 510
  ///
  /// If [excludeFromSemantics] is true, then [semanticLabel] will be ignored.
511
  ///
512 513 514 515 516 517
  /// If [cacheWidth] or [cacheHeight] are provided, it indicates to the
  /// engine that the image must be decoded at the specified size. The image
  /// will be rendered to the constraints of the layout or [width] and [height]
  /// regardless of these parameters. These parameters are primarily intended
  /// to reduce the memory usage of [ImageCache].
  ///
518
  /// The [name] and [repeat] arguments must not be null.
519
  ///
Ian Hickson's avatar
Ian Hickson committed
520 521 522 523 524
  /// Either the [width] and [height] arguments should be specified, or the
  /// widget should be placed in a context that sets tight layout constraints.
  /// Otherwise, the image dimensions will change as the image is loaded, which
  /// will result in ugly layout changes.
  ///
525 526 527 528 529
  /// Use [filterQuality] to change the quality when scaling an image.
  /// Use the [FilterQuality.low] quality setting to scale the image,
  /// which corresponds to bilinear interpolation, rather than the default
  /// [FilterQuality.none] which corresponds to nearest-neighbor.
  ///
530
  /// {@tool snippet}
531 532 533 534 535 536 537 538 539 540
  ///
  /// Suppose that the project's `pubspec.yaml` file contains the following:
  ///
  /// ```yaml
  /// flutter:
  ///   assets:
  ///     - images/cat.png
  ///     - images/2x/cat.png
  ///     - images/3.5x/cat.png
  /// ```
541
  /// {@end-tool}
542 543 544 545 546
  ///
  /// On a screen with a device pixel ratio of 2.0, the following widget would
  /// render the `images/2x/cat.png` file:
  ///
  /// ```dart
547
  /// Image.asset('images/cat.png')
548 549 550 551 552 553
  /// ```
  ///
  /// This corresponds to the file that is in the project's `images/2x/`
  /// directory with the name `cat.png` (the paths are relative to the
  /// `pubspec.yaml` file).
  ///
554 555 556 557 558 559 560 561
  /// On a device with a 4.0 device pixel ratio, the `images/3.5x/cat.png` asset
  /// would be used. On a device with a 1.0 device pixel ratio, the
  /// `images/cat.png` resource would be used.
  ///
  /// The `images/cat.png` image can be omitted from disk (though it must still
  /// be present in the manifest). If it is omitted, then on a device with a 1.0
  /// device pixel ratio, the `images/2x/cat.png` image would be used instead.
  ///
562 563 564 565 566 567 568
  ///
  /// ## Assets in packages
  ///
  /// To create the widget with an asset from a package, the [package] argument
  /// must be provided. For instance, suppose a package called `my_icons` has
  /// `icons/heart.png` .
  ///
569
  /// {@tool snippet}
570 571 572
  /// Then to display the image, use:
  ///
  /// ```dart
573
  /// Image.asset('icons/heart.png', package: 'my_icons')
574
  /// ```
575
  /// {@end-tool}
576 577 578 579
  ///
  /// Assets used by the package itself should also be displayed using the
  /// [package] argument as above.
  ///
580
  /// If the desired asset is specified in the `pubspec.yaml` of the package, it
581
  /// is bundled automatically with the app. In particular, assets used by the
582
  /// package itself must be specified in its `pubspec.yaml`.
583 584
  ///
  /// A package can also choose to have assets in its 'lib/' folder that are not
585
  /// specified in its `pubspec.yaml`. In this case for those images to be
586 587 588 589 590 591 592
  /// 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
593
  /// ```
594
  ///
595
  /// To include, say the first image, the `pubspec.yaml` of the app should
596 597 598
  /// specify it in the assets section:
  ///
  /// ```yaml
599 600
  ///   assets:
  ///     - packages/fancy_backgrounds/backgrounds/background1.png
601 602
  /// ```
  ///
Ian Hickson's avatar
Ian Hickson committed
603
  /// The `lib/` is implied, so it should not be included in the asset path.
604 605
  ///
  ///
606 607 608 609 610 611
  /// See also:
  ///
  ///  * [AssetImage], which is used to implement the behavior when the scale is
  ///    omitted.
  ///  * [ExactAssetImage], which is used to implement the behavior when the
  ///    scale is present.
612
  ///  * <https://flutter.dev/assets-and-images/>, an introduction to assets in
613
  ///    Flutter.
614 615
  Image.asset(
    String name, {
616 617
    Key key,
    AssetBundle bundle,
618
    this.frameBuilder,
619
    this.errorBuilder,
620 621
    this.semanticLabel,
    this.excludeFromSemantics = false,
622 623 624 625
    double scale,
    this.width,
    this.height,
    this.color,
626
    this.colorBlendMode,
627
    this.fit,
628 629
    this.alignment = Alignment.center,
    this.repeat = ImageRepeat.noRepeat,
630
    this.centerSlice,
631 632
    this.matchTextDirection = false,
    this.gaplessPlayback = false,
633
    this.isAntiAlias = false,
Ian Hickson's avatar
Ian Hickson committed
634
    String package,
635
    this.filterQuality = FilterQuality.low,
636 637
    int cacheWidth,
    int cacheHeight,
638
  }) : image = ResizeImage.resizeIfNeeded(cacheWidth, cacheHeight, scale != null
639
         ? ExactAssetImage(name, bundle: bundle, scale: scale, package: package)
640 641
         : AssetImage(name, bundle: bundle, package: package)
       ),
642
       loadingBuilder = null,
Ian Hickson's avatar
Ian Hickson committed
643 644 645
       assert(alignment != null),
       assert(repeat != null),
       assert(matchTextDirection != null),
646 647
       assert(cacheWidth == null || cacheWidth > 0),
       assert(cacheHeight == null || cacheHeight > 0),
648
       assert(isAntiAlias != null),
Ian Hickson's avatar
Ian Hickson committed
649
       super(key: key);
650

651 652 653
  /// Creates a widget that displays an [ImageStream] obtained from a [Uint8List].
  ///
  /// The [bytes], [scale], and [repeat] arguments must not be null.
Ian Hickson's avatar
Ian Hickson committed
654
  ///
655
  /// This only accepts compressed image formats (e.g. PNG). Uncompressed
656 657
  /// formats like rawRgba (the default format of [dart:ui.Image.toByteData])
  /// will lead to exceptions.
658
  ///
Ian Hickson's avatar
Ian Hickson committed
659 660 661 662
  /// Either the [width] and [height] arguments should be specified, or the
  /// widget should be placed in a context that sets tight layout constraints.
  /// Otherwise, the image dimensions will change as the image is loaded, which
  /// will result in ugly layout changes.
663
  ///
664 665 666 667 668
  /// Use [filterQuality] to change the quality when scaling an image.
  /// Use the [FilterQuality.low] quality setting to scale the image,
  /// which corresponds to bilinear interpolation, rather than the default
  /// [FilterQuality.none] which corresponds to nearest-neighbor.
  ///
669
  /// If [excludeFromSemantics] is true, then [semanticLabel] will be ignored.
670 671 672 673 674 675
  ///
  /// If [cacheWidth] or [cacheHeight] are provided, it indicates to the
  /// engine that the image must be decoded at the specified size. The image
  /// will be rendered to the constraints of the layout or [width] and [height]
  /// regardless of these parameters. These parameters are primarily intended
  /// to reduce the memory usage of [ImageCache].
676 677
  Image.memory(
    Uint8List bytes, {
678
    Key key,
679
    double scale = 1.0,
680
    this.frameBuilder,
681
    this.errorBuilder,
682 683
    this.semanticLabel,
    this.excludeFromSemantics = false,
684 685 686
    this.width,
    this.height,
    this.color,
687
    this.colorBlendMode,
688
    this.fit,
689 690
    this.alignment = Alignment.center,
    this.repeat = ImageRepeat.noRepeat,
691
    this.centerSlice,
692 693
    this.matchTextDirection = false,
    this.gaplessPlayback = false,
694
    this.isAntiAlias = false,
695
    this.filterQuality = FilterQuality.low,
696 697
    int cacheWidth,
    int cacheHeight,
698
  }) : image = ResizeImage.resizeIfNeeded(cacheWidth, cacheHeight, MemoryImage(bytes, scale: scale)),
699
       loadingBuilder = null,
Ian Hickson's avatar
Ian Hickson committed
700 701 702
       assert(alignment != null),
       assert(repeat != null),
       assert(matchTextDirection != null),
703 704
       assert(cacheWidth == null || cacheWidth > 0),
       assert(cacheHeight == null || cacheHeight > 0),
705
       assert(isAntiAlias != null),
706 707
       super(key: key);

708 709 710
  /// The image to display.
  final ImageProvider image;

711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
  /// A builder function responsible for creating the widget that represents
  /// this image.
  ///
  /// If this is null, this widget will display an image that is painted as
  /// soon as the first image frame is available (and will appear to "pop" in
  /// if it becomes available asynchronously). Callers might use this builder to
  /// add effects to the image (such as fading the image in when it becomes
  /// available) or to display a placeholder widget while the image is loading.
  ///
  /// To have finer-grained control over the way that an image's loading
  /// progress is communicated to the user, see [loadingBuilder].
  ///
  /// ## Chaining with [loadingBuilder]
  ///
  /// If a [loadingBuilder] has _also_ been specified for an image, the two
  /// builders will be chained together: the _result_ of this builder will
  /// be passed as the `child` argument to the [loadingBuilder]. For example,
  /// consider the following builders used in conjunction:
  ///
  /// {@template flutter.widgets.image.chainedBuildersExample}
  /// ```dart
  /// Image(
  ///   ...
  ///   frameBuilder: (BuildContext context, Widget child, int frame, bool wasSynchronouslyLoaded) {
  ///     return Padding(
  ///       padding: EdgeInsets.all(8.0),
  ///       child: child,
  ///     );
  ///   },
  ///   loadingBuilder: (BuildContext context, Widget child, ImageChunkEvent loadingProgress) {
  ///     return Center(child: child);
  ///   },
  /// )
  /// ```
  ///
  /// In this example, the widget hierarchy will contain the following:
  ///
  /// ```dart
  /// Center(
  ///   Padding(
  ///     padding: EdgeInsets.all(8.0),
  ///     child: <image>,
  ///   ),
  /// )
  /// ```
  /// {@endtemplate}
  ///
758
  /// {@tool dartpad --template=stateless_widget_material}
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
  ///
  /// The following sample demonstrates how to use this builder to implement an
  /// image that fades in once it's been loaded.
  ///
  /// This sample contains a limited subset of the functionality that the
  /// [FadeInImage] widget provides out of the box.
  ///
  /// ```dart
  /// @override
  /// Widget build(BuildContext context) {
  ///   return DecoratedBox(
  ///     decoration: BoxDecoration(
  ///       color: Colors.white,
  ///       border: Border.all(),
  ///       borderRadius: BorderRadius.circular(20),
  ///     ),
  ///     child: Image.network(
776
  ///       'https://flutter.github.io/assets-for-api-docs/assets/widgets/puffin.jpg',
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
  ///       frameBuilder: (BuildContext context, Widget child, int frame, bool wasSynchronouslyLoaded) {
  ///         if (wasSynchronouslyLoaded) {
  ///           return child;
  ///         }
  ///         return AnimatedOpacity(
  ///           child: child,
  ///           opacity: frame == null ? 0 : 1,
  ///           duration: const Duration(seconds: 1),
  ///           curve: Curves.easeOut,
  ///         );
  ///       },
  ///     ),
  ///   );
  /// }
  /// ```
  /// {@end-tool}
  final ImageFrameBuilder frameBuilder;

  /// A builder that specifies the widget to display to the user while an image
  /// is still loading.
  ///
  /// If this is null, and the image is loaded incrementally (e.g. over a
  /// network), the user will receive no indication of the progress as the
  /// bytes of the image are loaded.
  ///
  /// For more information on how to interpret the arguments that are passed to
  /// this builder, see the documentation on [ImageLoadingBuilder].
  ///
  /// ## Performance implications
  ///
  /// If a [loadingBuilder] is specified for an image, the [Image] widget is
  /// likely to be rebuilt on every
  /// [rendering pipeline frame](rendering/RendererBinding/drawFrame.html) until
  /// the image has loaded. This is useful for cases such as displaying a loading
  /// progress indicator, but for simpler cases such as displaying a placeholder
  /// widget that doesn't depend on the loading progress (e.g. static "loading"
  /// text), [frameBuilder] will likely work and not incur as much cost.
  ///
  /// ## Chaining with [frameBuilder]
  ///
  /// If a [frameBuilder] has _also_ been specified for an image, the two
  /// builders will be chained together: the `child` argument to this
  /// builder will contain the _result_ of the [frameBuilder]. For example,
  /// consider the following builders used in conjunction:
  ///
  /// {@macro flutter.widgets.image.chainedBuildersExample}
  ///
824
  /// {@tool dartpad --template=stateless_widget_material}
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
  ///
  /// The following sample uses [loadingBuilder] to show a
  /// [CircularProgressIndicator] while an image loads over the network.
  ///
  /// ```dart
  /// Widget build(BuildContext context) {
  ///   return DecoratedBox(
  ///     decoration: BoxDecoration(
  ///       color: Colors.white,
  ///       border: Border.all(),
  ///       borderRadius: BorderRadius.circular(20),
  ///     ),
  ///     child: Image.network(
  ///       'https://example.com/image.jpg',
  ///       loadingBuilder: (BuildContext context, Widget child, ImageChunkEvent loadingProgress) {
  ///         if (loadingProgress == null)
  ///           return child;
  ///         return Center(
  ///           child: CircularProgressIndicator(
  ///             value: loadingProgress.expectedTotalBytes != null
  ///                 ? loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes
  ///                 : null,
  ///           ),
  ///         );
  ///       },
  ///     ),
  ///   );
  /// }
  /// ```
  /// {@end-tool}
  ///
856 857 858
  /// Run against a real-world image on a slow network, the previous example
  /// renders the following loading progress indicator while the image loads
  /// before rendering the completed image.
859 860 861 862
  ///
  /// {@animation 400 400 https://flutter.github.io/assets-for-api-docs/assets/widgets/loading_progress_image.mp4}
  final ImageLoadingBuilder loadingBuilder;

863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
  /// A builder function that is called if an error occurs during image loading.
  ///
  /// If this builder is not provided, any exceptions will be reported to
  /// [FlutterError.onError]. If it is provided, the caller should either handle
  /// the exception by providing a replacement widget, or rethrow the exception.
  ///
  /// {@tool dartpad --template=stateless_widget_material}
  ///
  /// The following sample uses [errorBuilder] to show a '😢' in place of the
  /// image that fails to load, and prints the error to the console.
  ///
  /// ```dart
  /// Widget build(BuildContext context) {
  ///   return DecoratedBox(
  ///     decoration: BoxDecoration(
  ///       color: Colors.white,
  ///       border: Border.all(),
  ///       borderRadius: BorderRadius.circular(20),
  ///     ),
  ///     child: Image.network(
  ///       'https://example.does.not.exist/image.jpg',
  ///       errorBuilder: (BuildContext context, Object exception, StackTrace stackTrace) {
  ///         // Appropriate logging or analytics, e.g.
  ///         // myAnalytics.recordError(
  ///         //   'An error occurred loading "https://example.does.not.exist/image.jpg"',
  ///         //   exception,
  ///         //   stackTrace,
  ///         // );
  ///         return Text('😢');
  ///       },
  ///     ),
  ///   );
  /// }
  /// ```
  /// {@end-tool}
  final ImageErrorWidgetBuilder errorBuilder;

900 901 902 903
  /// If non-null, require the image to have this width.
  ///
  /// If null, the image will pick a size that best preserves its intrinsic
  /// aspect ratio.
Ian Hickson's avatar
Ian Hickson committed
904 905 906 907 908 909
  ///
  /// It is strongly recommended that either both the [width] and the [height]
  /// be specified, or that the widget be placed in a context that sets tight
  /// layout constraints, so that the image does not change size as it loads.
  /// Consider using [fit] to adapt the image's rendering to fit the given width
  /// and height if the exact image dimensions are not known in advance.
910 911 912 913 914 915
  final double width;

  /// If non-null, require the image to have this height.
  ///
  /// If null, the image will pick a size that best preserves its intrinsic
  /// aspect ratio.
Ian Hickson's avatar
Ian Hickson committed
916 917 918 919 920 921
  ///
  /// It is strongly recommended that either both the [width] and the [height]
  /// be specified, or that the widget be placed in a context that sets tight
  /// layout constraints, so that the image does not change size as it loads.
  /// Consider using [fit] to adapt the image's rendering to fit the given width
  /// and height if the exact image dimensions are not known in advance.
922 923
  final double height;

924
  /// If non-null, this color is blended with each image pixel using [colorBlendMode].
925 926
  final Color color;

927 928 929 930
  /// Used to set the [FilterQuality] of the image.
  ///
  /// Use the [FilterQuality.low] quality setting to scale the image with
  /// bilinear interpolation, or the [FilterQuality.none] which corresponds
931 932 933
  /// to nearest-neighbor.
  final FilterQuality filterQuality;

934 935 936 937 938 939 940 941 942 943
  /// Used to combine [color] with this image.
  ///
  /// The default is [BlendMode.srcIn]. In terms of the blend mode, [color] is
  /// the source and this image is the destination.
  ///
  /// See also:
  ///
  ///  * [BlendMode], which includes an illustration of the effect of each blend mode.
  final BlendMode colorBlendMode;

Adam Barth's avatar
Adam Barth committed
944
  /// How to inscribe the image into the space allocated during layout.
945 946 947
  ///
  /// The default varies based on the other fields. See the discussion at
  /// [paintImage].
948
  final BoxFit fit;
949 950 951

  /// How to align the image within its bounds.
  ///
Ian Hickson's avatar
Ian Hickson committed
952
  /// The alignment aligns the given position in the image to the given position
953 954
  /// in the layout bounds. For example, an [Alignment] alignment of (-1.0,
  /// -1.0) aligns the image to the top-left corner of its layout bounds, while an
955
  /// [Alignment] alignment of (1.0, 1.0) aligns the bottom right of the
Ian Hickson's avatar
Ian Hickson committed
956
  /// image with the bottom right corner of its layout bounds. Similarly, an
957
  /// alignment of (0.0, 1.0) aligns the bottom middle of the image with the
Ian Hickson's avatar
Ian Hickson committed
958 959 960 961 962 963
  /// middle of the bottom edge of its layout bounds.
  ///
  /// To display a subpart of an image, consider using a [CustomPainter] and
  /// [Canvas.drawImageRect].
  ///
  /// If the [alignment] is [TextDirection]-dependent (i.e. if it is a
964
  /// [AlignmentDirectional]), then an ambient [Directionality] widget
Ian Hickson's avatar
Ian Hickson committed
965 966
  /// must be in scope.
  ///
967
  /// Defaults to [Alignment.center].
968 969 970 971 972 973 974
  ///
  /// See also:
  ///
  ///  * [Alignment], a class with convenient constants typically used to
  ///    specify an [AlignmentGeometry].
  ///  * [AlignmentDirectional], like [Alignment] for specifying alignments
  ///    relative to text direction.
975
  final AlignmentGeometry alignment;
976 977 978 979 980 981 982 983 984 985 986 987 988

  /// How to paint any portions of the layout bounds not covered by the image.
  final ImageRepeat repeat;

  /// The center slice for a nine-patch image.
  ///
  /// The region of the image inside the center slice will be stretched both
  /// horizontally and vertically to fit the image into its destination. The
  /// region of the image above and below the center slice will be stretched
  /// only horizontally and the region of the image to the left and right of
  /// the center slice will be stretched only vertically.
  final Rect centerSlice;

Ian Hickson's avatar
Ian Hickson committed
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
  /// Whether to paint the image in the direction of the [TextDirection].
  ///
  /// If this is true, then in [TextDirection.ltr] contexts, the image will be
  /// drawn with its origin in the top left (the "normal" painting direction for
  /// images); and in [TextDirection.rtl] contexts, the image will be drawn with
  /// a scaling factor of -1 in the horizontal direction so that the origin is
  /// in the top right.
  ///
  /// This is occasionally used with images in right-to-left environments, for
  /// images that were designed for left-to-right locales. Be careful, when
  /// using this, to not flip images with integral shadows, text, or other
  /// effects that will look incorrect when flipped.
  ///
  /// If this is true, there must be an ambient [Directionality] widget in
  /// scope.
  final bool matchTextDirection;

1006
  /// Whether to continue showing the old image (true), or briefly show nothing
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
  /// (false), when the image provider changes. The default value is false.
  ///
  /// ## Design discussion
  ///
  /// ### Why is the default value of [gaplessPlayback] false?
  ///
  /// Having the default value of [gaplessPlayback] be false helps prevent
  /// situations where stale or misleading information might be presented.
  /// Consider the following case:
  ///
  /// We have constructed a 'Person' widget that displays an avatar [Image] of
  /// the currently loaded person along with their name. We could request for a
  /// new person to be loaded into the widget at any time. Suppose we have a
  /// person currently loaded and the widget loads a new person. What happens
  /// if the [Image] fails to load?
  ///
  /// * Option A ([gaplessPlayback] = false): The new person's name is coupled
  /// with a blank image.
  ///
  /// * Option B ([gaplessPlayback] = true): The widget displays the avatar of
  /// the previous person and the name of the newly loaded person.
  ///
  /// This is why the default value is false. Most of the time, when you change
  /// the image provider you're not just changing the image, you're removing the
  /// old widget and adding a new one and not expecting them to have any
  /// relationship. With [gaplessPlayback] on you might accidentally break this
  /// expectation and re-use the old widget.
1034 1035
  final bool gaplessPlayback;

1036 1037
  /// A Semantic description of the image.
  ///
1038
  /// Used to provide a description of the image to TalkBack on Android, and
1039 1040 1041 1042 1043 1044 1045 1046 1047
  /// VoiceOver on iOS.
  final String semanticLabel;

  /// Whether to exclude this image from semantics.
  ///
  /// Useful for images which do not contribute meaningful information to an
  /// application.
  final bool excludeFromSemantics;

1048 1049 1050 1051 1052
  /// Whether to paint the image with anti-aliasing.
  ///
  /// Anti-aliasing alleviates the sawtooth artifact when the image is rotated.
  final bool isAntiAlias;

1053
  @override
1054
  _ImageState createState() => _ImageState();
1055 1056

  @override
1057 1058
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
1059
    properties.add(DiagnosticsProperty<ImageProvider>('image', image));
1060 1061
    properties.add(DiagnosticsProperty<Function>('frameBuilder', frameBuilder));
    properties.add(DiagnosticsProperty<Function>('loadingBuilder', loadingBuilder));
1062 1063
    properties.add(DoubleProperty('width', width, defaultValue: null));
    properties.add(DoubleProperty('height', height, defaultValue: null));
1064
    properties.add(ColorProperty('color', color, defaultValue: null));
1065 1066 1067 1068 1069 1070 1071 1072
    properties.add(EnumProperty<BlendMode>('colorBlendMode', colorBlendMode, defaultValue: null));
    properties.add(EnumProperty<BoxFit>('fit', fit, defaultValue: null));
    properties.add(DiagnosticsProperty<AlignmentGeometry>('alignment', alignment, defaultValue: null));
    properties.add(EnumProperty<ImageRepeat>('repeat', repeat, defaultValue: ImageRepeat.noRepeat));
    properties.add(DiagnosticsProperty<Rect>('centerSlice', centerSlice, defaultValue: null));
    properties.add(FlagProperty('matchTextDirection', value: matchTextDirection, ifTrue: 'match text direction'));
    properties.add(StringProperty('semanticLabel', semanticLabel, defaultValue: null));
    properties.add(DiagnosticsProperty<bool>('this.excludeFromSemantics', excludeFromSemantics));
1073
    properties.add(EnumProperty<FilterQuality>('filterQuality', filterQuality));
1074 1075 1076
  }
}

1077
class _ImageState extends State<Image> with WidgetsBindingObserver {
1078 1079
  ImageStream _imageStream;
  ImageInfo _imageInfo;
1080
  ImageChunkEvent _loadingProgress;
1081
  bool _isListeningToStream = false;
1082
  bool _invertColors;
1083 1084
  int _frameNumber;
  bool _wasSynchronouslyLoaded;
1085
  DisposableBuildContext<State<Image>> _scrollAwareContext;
1086 1087
  Object _lastException;
  StackTrace _lastStack;
1088 1089 1090 1091 1092

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
1093
    _scrollAwareContext = DisposableBuildContext<State<Image>>(this);
1094 1095 1096 1097 1098 1099 1100
  }

  @override
  void dispose() {
    assert(_imageStream != null);
    WidgetsBinding.instance.removeObserver(this);
    _stopListeningToStream();
1101
    _scrollAwareContext.dispose();
1102 1103
    super.dispose();
  }
1104 1105

  @override
1106
  void didChangeDependencies() {
1107
    _updateInvertColors();
1108
    _resolveImage();
1109 1110 1111 1112 1113 1114

    if (TickerMode.of(context))
      _listenToStream();
    else
      _stopListeningToStream();

1115
    super.didChangeDependencies();
1116 1117
  }

1118
  @override
1119
  void didUpdateWidget(Image oldWidget) {
1120
    super.didUpdateWidget(oldWidget);
1121 1122
    if (_isListeningToStream &&
        (widget.loadingBuilder == null) != (oldWidget.loadingBuilder == null)) {
1123 1124
      _imageStream.removeListener(_getListener());
      _imageStream.addListener(_getListener(recreateListener: true));
1125
    }
1126
    if (widget.image != oldWidget.image)
1127 1128 1129
      _resolveImage();
  }

1130 1131 1132 1133 1134 1135 1136 1137
  @override
  void didChangeAccessibilityFeatures() {
    super.didChangeAccessibilityFeatures();
    setState(() {
      _updateInvertColors();
    });
  }

1138 1139
  @override
  void reassemble() {
1140
    _resolveImage(); // in case the image cache was flushed
1141 1142 1143
    super.reassemble();
  }

1144 1145 1146 1147 1148
  void _updateInvertColors() {
    _invertColors = MediaQuery.of(context, nullOk: true)?.invertColors
        ?? SemanticsBinding.instance.accessibilityFeatures.invertColors;
  }

1149
  void _resolveImage() {
1150 1151 1152 1153
    final ScrollAwareImageProvider provider = ScrollAwareImageProvider<dynamic>(
      context: _scrollAwareContext,
      imageProvider: widget.image,
    );
1154
    final ImageStream newStream =
1155
      provider.resolve(createLocalImageConfiguration(
1156 1157
        context,
        size: widget.width != null && widget.height != null ? Size(widget.width, widget.height) : null,
1158 1159 1160
      ));
    assert(newStream != null);
    _updateSourceStream(newStream);
1161 1162
  }

1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
  ImageStreamListener _imageStreamListener;
  ImageStreamListener _getListener({bool recreateListener = false}) {
    if(_imageStreamListener == null || recreateListener) {
      _lastException = null;
      _lastStack = null;
      _imageStreamListener = ImageStreamListener(
        _handleImageFrame,
        onChunk: widget.loadingBuilder == null ? null : _handleImageChunk,
        onError: widget.errorBuilder != null
            ? (dynamic error, StackTrace stackTrace) {
                setState(() {
                  _lastException = error;
                  _lastStack = stackTrace;
                });
              }
            : null,
      );
    }
    return _imageStreamListener;
1182 1183 1184
  }

  void _handleImageFrame(ImageInfo imageInfo, bool synchronousCall) {
1185 1186
    setState(() {
      _imageInfo = imageInfo;
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
      _loadingProgress = null;
      _frameNumber = _frameNumber == null ? 0 : _frameNumber + 1;
      _wasSynchronouslyLoaded |= synchronousCall;
    });
  }

  void _handleImageChunk(ImageChunkEvent event) {
    assert(widget.loadingBuilder != null);
    setState(() {
      _loadingProgress = event;
1197 1198 1199
    });
  }

1200
  // Updates _imageStream to newStream, and moves the stream listener
1201 1202 1203 1204 1205 1206 1207
  // registration from the old stream to the new stream (if a listener was
  // registered).
  void _updateSourceStream(ImageStream newStream) {
    if (_imageStream?.key == newStream?.key)
      return;

    if (_isListeningToStream)
1208
      _imageStream.removeListener(_getListener());
1209

1210 1211 1212
    if (!widget.gaplessPlayback)
      setState(() { _imageInfo = null; });

1213 1214 1215 1216 1217 1218
    setState(() {
      _loadingProgress = null;
      _frameNumber = null;
      _wasSynchronouslyLoaded = false;
    });

1219 1220
    _imageStream = newStream;
    if (_isListeningToStream)
1221
      _imageStream.addListener(_getListener());
1222 1223 1224 1225 1226
  }

  void _listenToStream() {
    if (_isListeningToStream)
      return;
1227
    _imageStream.addListener(_getListener());
1228 1229 1230 1231 1232 1233
    _isListeningToStream = true;
  }

  void _stopListeningToStream() {
    if (!_isListeningToStream)
      return;
1234
    _imageStream.removeListener(_getListener());
1235 1236 1237
    _isListeningToStream = false;
  }

1238 1239
  @override
  Widget build(BuildContext context) {
1240 1241 1242 1243 1244
    if (_lastException  != null) {
      assert(widget.errorBuilder != null);
      return widget.errorBuilder(context, _lastException, _lastStack);
    }

1245
    Widget result = RawImage(
1246
      image: _imageInfo?.image,
1247
      debugImageLabel: _imageInfo?.debugLabel,
1248 1249
      width: widget.width,
      height: widget.height,
1250
      scale: _imageInfo?.scale ?? 1.0,
1251
      color: widget.color,
1252
      colorBlendMode: widget.colorBlendMode,
1253 1254 1255
      fit: widget.fit,
      alignment: widget.alignment,
      repeat: widget.repeat,
Ian Hickson's avatar
Ian Hickson committed
1256 1257
      centerSlice: widget.centerSlice,
      matchTextDirection: widget.matchTextDirection,
1258
      invertColors: _invertColors,
1259
      isAntiAlias: widget.isAntiAlias,
1260
      filterQuality: widget.filterQuality,
1261
    );
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278

    if (!widget.excludeFromSemantics) {
      result = Semantics(
        container: widget.semanticLabel != null,
        image: true,
        label: widget.semanticLabel ?? '',
        child: result,
      );
    }

    if (widget.frameBuilder != null)
      result = widget.frameBuilder(context, result, _frameNumber, _wasSynchronouslyLoaded);

    if (widget.loadingBuilder != null)
      result = widget.loadingBuilder(context, result, _loadingProgress);

    return result;
1279
  }
1280 1281

  @override
1282
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
1283
    super.debugFillProperties(description);
1284 1285
    description.add(DiagnosticsProperty<ImageStream>('stream', _imageStream));
    description.add(DiagnosticsProperty<ImageInfo>('pixels', _imageInfo));
1286 1287 1288
    description.add(DiagnosticsProperty<ImageChunkEvent>('loadingProgress', _loadingProgress));
    description.add(DiagnosticsProperty<int>('frameNumber', _frameNumber));
    description.add(DiagnosticsProperty<bool>('wasSynchronouslyLoaded', _wasSynchronouslyLoaded));
1289
  }
1290
}