image.dart 51.5 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
import 'dart:async';
6
import 'dart:io' show File;
7
import 'dart:typed_data';
8

9
import 'package:flutter/foundation.dart';
Dan Field's avatar
Dan Field committed
10
import 'package:flutter/scheduler.dart';
11
import 'package:flutter/semantics.dart';
12
import 'package:flutter/services.dart';
13 14

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

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

37 38 39 40 41
/// 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].
42 43 44
///
/// If this is not called from a build method, then it should be reinvoked
/// whenever the dependencies change, e.g. by calling it from
45
/// [State.didChangeDependencies], so that any changes in the environment are
46 47 48 49 50
/// picked up (e.g. if the device pixel ratio changes).
///
/// See also:
///
///  * [ImageProvider], which has an example showing how this might be used.
51
ImageConfiguration createLocalImageConfiguration(BuildContext context, { Size? size }) {
52
  return ImageConfiguration(
53
    bundle: DefaultAssetBundle.of(context),
54
    devicePixelRatio: MediaQuery.maybeOf(context)?.devicePixelRatio ?? 1.0,
55
    locale: Localizations.maybeLocaleOf(context),
56
    textDirection: Directionality.maybeOf(context),
57
    size: size,
58
    platform: defaultTargetPlatform,
59 60 61
  );
}

62 63 64
/// Prefetches an image into the image cache.
///
/// Returns a [Future] that will complete when the first image yielded by the
65
/// [ImageProvider] is available or failed to load.
66 67
///
/// If the image is later used by an [Image] or [BoxDecoration] or [FadeInImage],
68 69
/// 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
70 71 72 73 74 75 76
/// 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.
///
77 78 79 80 81 82 83 84 85 86 87
/// 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
88 89 90
///
/// 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
91
/// killed by the operating system. The lower the available physical memory, the
Dan Field's avatar
Dan Field committed
92 93
/// more susceptible callers will be to running into OOM issues. These issues
/// manifest as immediate process death, sometimes with no other error messages.
94 95 96 97
///
/// The [BuildContext] and [Size] are used to select an image configuration
/// (see [createLocalImageConfiguration]).
///
98 99
/// The returned future will not complete with error, even if precaching
/// failed. The `onError` argument can be used to manually handle errors while
100
/// pre-caching.
101
///
102 103
/// See also:
///
104
///  * [ImageCache], which holds images that may be reused.
105
Future<void> precacheImage(
106 107
  ImageProvider provider,
  BuildContext context, {
108 109
  Size? size,
  ImageErrorListener? onError,
110
}) {
111
  final ImageConfiguration config = createLocalImageConfiguration(context, size: size);
112
  final Completer<void> completer = Completer<void>();
113
  final ImageStream stream = provider.resolve(config);
114
  ImageStreamListener? listener;
115
  listener = ImageStreamListener(
116
    (ImageInfo? image, bool sync) {
117 118 119
      if (!completer.isCompleted) {
        completer.complete();
      }
Dan Field's avatar
Dan Field committed
120 121 122
      // Give callers until at least the end of the frame to subscribe to the
      // image stream.
      // See ImageCache._liveImages
123 124
      SchedulerBinding.instance!.addPostFrameCallback((Duration timeStamp) {
        stream.removeListener(listener!);
Dan Field's avatar
Dan Field committed
125
      });
126
    },
127
    onError: (Object exception, StackTrace? stackTrace) {
128 129 130
      if (!completer.isCompleted) {
        completer.complete();
      }
131
      stream.removeListener(listener!);
132 133 134 135 136 137 138 139 140 141 142 143 144 145
      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
/// 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,
183
  int? frame,
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
  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,
223
  ImageChunkEvent? loadingProgress,
224 225
);

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

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
  /// {@template flutter.widgets.image.filterQualityParameter}
  /// Use [filterQuality] to specify the rendering quality of the image.
  /// {@endtemplate}
320
  ///
321
  /// If [excludeFromSemantics] is true, then [semanticLabel] will be ignored.
322
  const Image({
323 324
    Key? key,
    required this.image,
325 326
    this.frameBuilder,
    this.loadingBuilder,
327
    this.errorBuilder,
328 329
    this.semanticLabel,
    this.excludeFromSemantics = false,
330 331 332
    this.width,
    this.height,
    this.color,
333
    this.colorBlendMode,
334
    this.fit,
335 336
    this.alignment = Alignment.center,
    this.repeat = ImageRepeat.noRepeat,
337
    this.centerSlice,
338 339
    this.matchTextDirection = false,
    this.gaplessPlayback = false,
340
    this.isAntiAlias = false,
341
    this.filterQuality = FilterQuality.low,
342
  }) : assert(image != null),
Ian Hickson's avatar
Ian Hickson committed
343 344
       assert(alignment != null),
       assert(repeat != null),
345
       assert(filterQuality != null),
Ian Hickson's avatar
Ian Hickson committed
346
       assert(matchTextDirection != null),
347
       assert(isAntiAlias != null),
348
       super(key: key);
349 350 351 352

  /// 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
353 354 355 356 357
  ///
  /// 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.
358 359
  ///
  /// All network images are cached regardless of HTTP headers.
Ian Hickson's avatar
Ian Hickson committed
360 361 362
  ///
  /// An optional [headers] argument can be used to send custom HTTP headers
  /// with the image request.
363
  ///
364
  /// {@macro flutter.widgets.image.filterQualityParameter}
365
  ///
366
  /// If [excludeFromSemantics] is true, then [semanticLabel] will be ignored.
367 368 369 370 371 372 373 374 375 376 377 378 379
  ///
  /// 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.
380 381
  Image.network(
    String src, {
382
    Key? key,
383
    double scale = 1.0,
384 385
    this.frameBuilder,
    this.loadingBuilder,
386
    this.errorBuilder,
387 388
    this.semanticLabel,
    this.excludeFromSemantics = false,
389 390 391
    this.width,
    this.height,
    this.color,
392
    this.colorBlendMode,
393
    this.fit,
394 395
    this.alignment = Alignment.center,
    this.repeat = ImageRepeat.noRepeat,
396
    this.centerSlice,
397 398
    this.matchTextDirection = false,
    this.gaplessPlayback = false,
399
    this.filterQuality = FilterQuality.low,
400
    this.isAntiAlias = false,
401 402 403
    Map<String, String>? headers,
    int? cacheWidth,
    int? cacheHeight,
404
  }) : image = ResizeImage.resizeIfNeeded(cacheWidth, cacheHeight, NetworkImage(src, scale: scale, headers: headers)),
Ian Hickson's avatar
Ian Hickson committed
405 406 407
       assert(alignment != null),
       assert(repeat != null),
       assert(matchTextDirection != null),
408 409
       assert(cacheWidth == null || cacheWidth > 0),
       assert(cacheHeight == null || cacheHeight > 0),
410
       assert(isAntiAlias != null),
411 412
       super(key: key);

Ian Hickson's avatar
Ian Hickson committed
413 414 415 416
  /// 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
417 418 419 420 421
  /// 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
422 423
  /// On Android, this may require the
  /// `android.permission.READ_EXTERNAL_STORAGE` permission.
424
  ///
425
  /// {@macro flutter.widgets.image.filterQualityParameter}
426
  ///
427
  /// If [excludeFromSemantics] is true, then [semanticLabel] will be ignored.
428 429 430 431 432 433
  ///
  /// 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].
434 435 436 437 438 439 440 441 442
  ///
  /// 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.
443 444
  Image.file(
    File file, {
445
    Key? key,
446
    double scale = 1.0,
447
    this.frameBuilder,
448
    this.errorBuilder,
449 450
    this.semanticLabel,
    this.excludeFromSemantics = false,
Ian Hickson's avatar
Ian Hickson committed
451 452 453
    this.width,
    this.height,
    this.color,
454
    this.colorBlendMode,
Ian Hickson's avatar
Ian Hickson committed
455
    this.fit,
456 457
    this.alignment = Alignment.center,
    this.repeat = ImageRepeat.noRepeat,
Ian Hickson's avatar
Ian Hickson committed
458
    this.centerSlice,
459 460
    this.matchTextDirection = false,
    this.gaplessPlayback = false,
461
    this.isAntiAlias = false,
462
    this.filterQuality = FilterQuality.low,
463 464
    int? cacheWidth,
    int? cacheHeight,
465
  }) : image = ResizeImage.resizeIfNeeded(cacheWidth, cacheHeight, FileImage(file, scale: scale)),
466
       loadingBuilder = null,
Ian Hickson's avatar
Ian Hickson committed
467 468
       assert(alignment != null),
       assert(repeat != null),
469
       assert(filterQuality != null),
Ian Hickson's avatar
Ian Hickson committed
470
       assert(matchTextDirection != null),
471 472
       assert(cacheWidth == null || cacheWidth > 0),
       assert(cacheHeight == null || cacheHeight > 0),
473
       assert(isAntiAlias != null),
Ian Hickson's avatar
Ian Hickson committed
474 475
       super(key: key);

476 477 478 479 480 481 482 483 484
  // 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.
485 486 487
  /// Creates a widget that displays an [ImageStream] obtained from an asset
  /// bundle. The key for the image is given by the `name` argument.
  ///
488 489 490 491
  /// 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.
  ///
492 493 494
  /// If the `bundle` argument is omitted or null, then the
  /// [DefaultAssetBundle] will be used.
  ///
495 496
  /// By default, the pixel-density-aware asset resolution will be attempted. In
  /// addition:
497
  ///
498
  /// * If the `scale` argument is provided and is not null, then the exact
499 500
  /// 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`).
501 502
  ///
  /// If [excludeFromSemantics] is true, then [semanticLabel] will be ignored.
503
  ///
504 505 506 507 508 509
  /// 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].
  ///
510
  /// The [name] and [repeat] arguments must not be null.
511
  ///
Ian Hickson's avatar
Ian Hickson committed
512 513 514 515 516
  /// 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.
  ///
517
  /// {@macro flutter.widgets.image.filterQualityParameter}
518
  ///
519
  /// {@tool snippet}
520 521 522 523 524 525 526 527 528 529
  ///
  /// 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
  /// ```
530
  /// {@end-tool}
531 532 533 534 535
  ///
  /// On a screen with a device pixel ratio of 2.0, the following widget would
  /// render the `images/2x/cat.png` file:
  ///
  /// ```dart
536
  /// Image.asset('images/cat.png')
537 538 539 540 541 542
  /// ```
  ///
  /// 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).
  ///
543 544 545 546 547 548 549 550
  /// 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.
  ///
551 552 553 554 555 556 557
  ///
  /// ## 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` .
  ///
558
  /// {@tool snippet}
559 560 561
  /// Then to display the image, use:
  ///
  /// ```dart
562
  /// Image.asset('icons/heart.png', package: 'my_icons')
563
  /// ```
564
  /// {@end-tool}
565 566 567 568
  ///
  /// Assets used by the package itself should also be displayed using the
  /// [package] argument as above.
  ///
569
  /// If the desired asset is specified in the `pubspec.yaml` of the package, it
570
  /// is bundled automatically with the app. In particular, assets used by the
571
  /// package itself must be specified in its `pubspec.yaml`.
572 573
  ///
  /// A package can also choose to have assets in its 'lib/' folder that are not
574
  /// specified in its `pubspec.yaml`. In this case for those images to be
575 576 577 578 579 580 581
  /// 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
582
  /// ```
583
  ///
584
  /// To include, say the first image, the `pubspec.yaml` of the app should
585 586 587
  /// specify it in the assets section:
  ///
  /// ```yaml
588 589
  ///   assets:
  ///     - packages/fancy_backgrounds/backgrounds/background1.png
590 591
  /// ```
  ///
Ian Hickson's avatar
Ian Hickson committed
592
  /// The `lib/` is implied, so it should not be included in the asset path.
593 594
  ///
  ///
595 596 597 598 599 600
  /// 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.
601
  ///  * <https://flutter.dev/assets-and-images/>, an introduction to assets in
602
  ///    Flutter.
603 604
  Image.asset(
    String name, {
605 606
    Key? key,
    AssetBundle? bundle,
607
    this.frameBuilder,
608
    this.errorBuilder,
609 610
    this.semanticLabel,
    this.excludeFromSemantics = false,
611
    double? scale,
612 613 614
    this.width,
    this.height,
    this.color,
615
    this.colorBlendMode,
616
    this.fit,
617 618
    this.alignment = Alignment.center,
    this.repeat = ImageRepeat.noRepeat,
619
    this.centerSlice,
620 621
    this.matchTextDirection = false,
    this.gaplessPlayback = false,
622
    this.isAntiAlias = false,
623
    String? package,
624
    this.filterQuality = FilterQuality.low,
625 626
    int? cacheWidth,
    int? cacheHeight,
627 628 629 630 631 632
  }) : image = ResizeImage.resizeIfNeeded(
         cacheWidth,
         cacheHeight,
         scale != null
           ? ExactAssetImage(name, bundle: bundle, scale: scale, package: package)
           : AssetImage(name, bundle: bundle, package: package),
633
       ),
634
       loadingBuilder = null,
Ian Hickson's avatar
Ian Hickson committed
635 636 637
       assert(alignment != null),
       assert(repeat != null),
       assert(matchTextDirection != null),
638 639
       assert(cacheWidth == null || cacheWidth > 0),
       assert(cacheHeight == null || cacheHeight > 0),
640
       assert(isAntiAlias != null),
Ian Hickson's avatar
Ian Hickson committed
641
       super(key: key);
642

643 644
  /// Creates a widget that displays an [ImageStream] obtained from a [Uint8List].
  ///
645 646 647 648 649 650 651 652 653
  /// The `bytes` argument specifies encoded image bytes, which can be encoded
  /// in any of the following supported image formats:
  /// {@macro flutter.dart:ui.imageFormats}
  ///
  /// The `scale` argument specifies the linear scale factor for drawing this
  /// image at its intended size and applies to both the width and the height.
  /// {@macro flutter.painting.imageInfo.scale}
  ///
  /// 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
  /// {@macro flutter.widgets.image.filterQualityParameter}
665
  ///
666
  /// If [excludeFromSemantics] is true, then [semanticLabel] will be ignored.
667 668 669 670 671 672
  ///
  /// 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].
673 674
  Image.memory(
    Uint8List bytes, {
675
    Key? key,
676
    double scale = 1.0,
677
    this.frameBuilder,
678
    this.errorBuilder,
679 680
    this.semanticLabel,
    this.excludeFromSemantics = false,
681 682 683
    this.width,
    this.height,
    this.color,
684
    this.colorBlendMode,
685
    this.fit,
686 687
    this.alignment = Alignment.center,
    this.repeat = ImageRepeat.noRepeat,
688
    this.centerSlice,
689 690
    this.matchTextDirection = false,
    this.gaplessPlayback = false,
691
    this.isAntiAlias = false,
692
    this.filterQuality = FilterQuality.low,
693 694
    int? cacheWidth,
    int? cacheHeight,
695
  }) : image = ResizeImage.resizeIfNeeded(cacheWidth, cacheHeight, MemoryImage(bytes, scale: scale)),
696
       loadingBuilder = null,
Ian Hickson's avatar
Ian Hickson committed
697 698 699
       assert(alignment != null),
       assert(repeat != null),
       assert(matchTextDirection != null),
700 701
       assert(cacheWidth == null || cacheWidth > 0),
       assert(cacheHeight == null || cacheHeight > 0),
702
       assert(isAntiAlias != null),
703 704
       super(key: key);

705 706 707
  /// The image to display.
  final ImageProvider image;

708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
  /// 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:
  ///
727
  /// {@template flutter.widgets.Image.frameBuilder.chainedBuildersExample}
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
  /// ```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}
  ///
755
  /// {@tool dartpad --template=stateless_widget_material}
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
  ///
  /// 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(
773
  ///       'https://flutter.github.io/assets-for-api-docs/assets/widgets/puffin.jpg',
774 775
  ///       frameBuilder: (BuildContext context, Widget child, int? frame, bool wasSynchronouslyLoaded) {
  ///         if (wasSynchronouslyLoaded) {
776 777 778 779 780 781 782 783 784 785 786 787 788 789
  ///           return child;
  ///         }
  ///         return AnimatedOpacity(
  ///           child: child,
  ///           opacity: frame == null ? 0 : 1,
  ///           duration: const Duration(seconds: 1),
  ///           curve: Curves.easeOut,
  ///         );
  ///       },
  ///     ),
  ///   );
  /// }
  /// ```
  /// {@end-tool}
790
  final ImageFrameBuilder? frameBuilder;
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

  /// 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:
  ///
819
  /// {@macro flutter.widgets.Image.frameBuilder.chainedBuildersExample}
820
  ///
821
  /// {@tool dartpad --template=stateless_widget_material}
822 823 824 825 826 827 828 829 830 831 832 833 834 835
  ///
  /// 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',
836
  ///       loadingBuilder: (BuildContext context, Widget child, ImageChunkEvent? loadingProgress) {
837
  ///         if (loadingProgress == null) {
838
  ///           return child;
839
  ///         }
840 841 842
  ///         return Center(
  ///           child: CircularProgressIndicator(
  ///             value: loadingProgress.expectedTotalBytes != null
843
  ///                 ? loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes!
844 845 846 847 848 849 850 851 852 853
  ///                 : null,
  ///           ),
  ///         );
  ///       },
  ///     ),
  ///   );
  /// }
  /// ```
  /// {@end-tool}
  ///
854 855 856
  /// 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.
857 858
  ///
  /// {@animation 400 400 https://flutter.github.io/assets-for-api-docs/assets/widgets/loading_progress_image.mp4}
859
  final ImageLoadingBuilder? loadingBuilder;
860

861 862 863 864 865 866
  /// 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.
  ///
867
  /// {@tool dartpad --template=stateless_widget_material}
868 869 870 871 872 873 874 875 876 877 878 879 880 881
  ///
  /// 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',
882
  ///       errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) {
883 884 885 886 887 888
  ///         // Appropriate logging or analytics, e.g.
  ///         // myAnalytics.recordError(
  ///         //   'An error occurred loading "https://example.does.not.exist/image.jpg"',
  ///         //   exception,
  ///         //   stackTrace,
  ///         // );
889
  ///         return const Text('😢');
890 891 892 893 894 895
  ///       },
  ///     ),
  ///   );
  /// }
  /// ```
  /// {@end-tool}
896
  final ImageErrorWidgetBuilder? errorBuilder;
897

898 899 900 901
  /// 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
902 903 904 905 906 907
  ///
  /// 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.
908
  final double? width;
909 910 911 912 913

  /// 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
914 915 916 917 918 919
  ///
  /// 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.
920
  final double? height;
921

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

925 926 927 928 929 930 931 932 933 934 935 936 937
  /// The rendering quality of the image.
  ///
  /// If the image is of a high quality and its pixels are perfectly aligned
  /// with the physical screen pixels, extra quality enhancement may not be
  /// necessary. If so, then [FilterQuality.none] would be the most efficient.
  ///
  /// If the pixels are not perfectly aligned with the screen pixels, or if the
  /// image itself is of a low quality, [FilterQuality.none] may produce
  /// undesirable artifacts. Consider using other [FilterQuality] values to
  /// improve the rendered image quality in this case. Pixels may be misaligned
  /// with the screen pixels as a result of transforms or scaling.
  ///
  /// See also:
938
  ///
939 940
  ///  * [FilterQuality], the enum containing all possible filter quality
  ///    options.
941 942
  final FilterQuality filterQuality;

943 944 945 946 947 948 949 950
  /// 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.
951
  final BlendMode? colorBlendMode;
952

Adam Barth's avatar
Adam Barth committed
953
  /// How to inscribe the image into the space allocated during layout.
954 955 956
  ///
  /// The default varies based on the other fields. See the discussion at
  /// [paintImage].
957
  final BoxFit? fit;
958 959 960

  /// How to align the image within its bounds.
  ///
Ian Hickson's avatar
Ian Hickson committed
961
  /// The alignment aligns the given position in the image to the given position
962 963
  /// 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
964
  /// [Alignment] alignment of (1.0, 1.0) aligns the bottom right of the
Ian Hickson's avatar
Ian Hickson committed
965
  /// image with the bottom right corner of its layout bounds. Similarly, an
966
  /// alignment of (0.0, 1.0) aligns the bottom middle of the image with the
Ian Hickson's avatar
Ian Hickson committed
967 968 969 970 971 972
  /// 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
973
  /// [AlignmentDirectional]), then an ambient [Directionality] widget
Ian Hickson's avatar
Ian Hickson committed
974 975
  /// must be in scope.
  ///
976
  /// Defaults to [Alignment.center].
977 978 979 980 981 982 983
  ///
  /// See also:
  ///
  ///  * [Alignment], a class with convenient constants typically used to
  ///    specify an [AlignmentGeometry].
  ///  * [AlignmentDirectional], like [Alignment] for specifying alignments
  ///    relative to text direction.
984
  final AlignmentGeometry alignment;
985 986 987 988 989 990 991 992 993 994 995

  /// 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.
996
  final Rect? centerSlice;
997

Ian Hickson's avatar
Ian Hickson committed
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
  /// 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;

1015
  /// Whether to continue showing the old image (true), or briefly show nothing
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
  /// (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.
1043 1044
  final bool gaplessPlayback;

1045 1046
  /// A Semantic description of the image.
  ///
1047
  /// Used to provide a description of the image to TalkBack on Android, and
1048
  /// VoiceOver on iOS.
1049
  final String? semanticLabel;
1050 1051 1052 1053 1054 1055 1056

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

1057 1058 1059 1060 1061
  /// Whether to paint the image with anti-aliasing.
  ///
  /// Anti-aliasing alleviates the sawtooth artifact when the image is rotated.
  final bool isAntiAlias;

1062
  @override
1063
  State<Image> createState() => _ImageState();
1064 1065

  @override
1066 1067
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
1068
    properties.add(DiagnosticsProperty<ImageProvider>('image', image));
1069 1070
    properties.add(DiagnosticsProperty<Function>('frameBuilder', frameBuilder));
    properties.add(DiagnosticsProperty<Function>('loadingBuilder', loadingBuilder));
1071 1072
    properties.add(DoubleProperty('width', width, defaultValue: null));
    properties.add(DoubleProperty('height', height, defaultValue: null));
1073
    properties.add(ColorProperty('color', color, defaultValue: null));
1074 1075 1076 1077 1078 1079 1080 1081
    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));
1082
    properties.add(EnumProperty<FilterQuality>('filterQuality', filterQuality));
1083 1084 1085
  }
}

1086
class _ImageState extends State<Image> with WidgetsBindingObserver {
1087 1088 1089
  ImageStream? _imageStream;
  ImageInfo? _imageInfo;
  ImageChunkEvent? _loadingProgress;
1090
  bool _isListeningToStream = false;
1091 1092 1093 1094 1095 1096
  late bool _invertColors;
  int? _frameNumber;
  bool _wasSynchronouslyLoaded = false;
  late DisposableBuildContext<State<Image>> _scrollAwareContext;
  Object? _lastException;
  StackTrace? _lastStack;
1097
  ImageStreamCompleterHandle? _completerHandle;
1098 1099 1100 1101

  @override
  void initState() {
    super.initState();
1102
    WidgetsBinding.instance!.addObserver(this);
1103
    _scrollAwareContext = DisposableBuildContext<State<Image>>(this);
1104 1105 1106 1107 1108
  }

  @override
  void dispose() {
    assert(_imageStream != null);
1109
    WidgetsBinding.instance!.removeObserver(this);
1110
    _stopListeningToStream();
1111
    _completerHandle?.dispose();
1112
    _scrollAwareContext.dispose();
1113
    _replaceImage(info: null);
1114 1115
    super.dispose();
  }
1116 1117

  @override
1118
  void didChangeDependencies() {
1119
    _updateInvertColors();
1120
    _resolveImage();
1121 1122 1123 1124

    if (TickerMode.of(context))
      _listenToStream();
    else
1125
      _stopListeningToStream(keepStreamAlive: true);
1126

1127
    super.didChangeDependencies();
1128 1129
  }

1130
  @override
1131
  void didUpdateWidget(Image oldWidget) {
1132
    super.didUpdateWidget(oldWidget);
1133 1134
    if (_isListeningToStream &&
        (widget.loadingBuilder == null) != (oldWidget.loadingBuilder == null)) {
1135
      final ImageStreamListener oldListener = _getListener();
1136
      _imageStream!.addListener(_getListener(recreateListener: true));
1137
      _imageStream!.removeListener(oldListener);
1138
    }
1139
    if (widget.image != oldWidget.image)
1140 1141 1142
      _resolveImage();
  }

1143 1144 1145 1146 1147 1148 1149 1150
  @override
  void didChangeAccessibilityFeatures() {
    super.didChangeAccessibilityFeatures();
    setState(() {
      _updateInvertColors();
    });
  }

1151 1152
  @override
  void reassemble() {
1153
    _resolveImage(); // in case the image cache was flushed
1154 1155 1156
    super.reassemble();
  }

1157
  void _updateInvertColors() {
1158
    _invertColors = MediaQuery.maybeOf(context)?.invertColors
1159
        ?? SemanticsBinding.instance!.accessibilityFeatures.invertColors;
1160 1161
  }

1162
  void _resolveImage() {
1163
    final ScrollAwareImageProvider provider = ScrollAwareImageProvider<Object>(
1164 1165 1166
      context: _scrollAwareContext,
      imageProvider: widget.image,
    );
1167
    final ImageStream newStream =
1168
      provider.resolve(createLocalImageConfiguration(
1169
        context,
1170
        size: widget.width != null && widget.height != null ? Size(widget.width!, widget.height!) : null,
1171 1172 1173
      ));
    assert(newStream != null);
    _updateSourceStream(newStream);
1174 1175
  }

1176
  ImageStreamListener? _imageStreamListener;
1177 1178 1179 1180 1181 1182 1183
  ImageStreamListener _getListener({bool recreateListener = false}) {
    if(_imageStreamListener == null || recreateListener) {
      _lastException = null;
      _lastStack = null;
      _imageStreamListener = ImageStreamListener(
        _handleImageFrame,
        onChunk: widget.loadingBuilder == null ? null : _handleImageChunk,
1184 1185
        onError: widget.errorBuilder != null || kDebugMode
            ? (Object error, StackTrace? stackTrace) {
1186 1187 1188 1189
                setState(() {
                  _lastException = error;
                  _lastStack = stackTrace;
                });
1190 1191 1192 1193 1194
                assert(() {
                  if (widget.errorBuilder == null)
                    throw error; // Ensures the error message is printed to the console.
                  return true;
                }());
1195 1196 1197 1198
              }
            : null,
      );
    }
1199
    return _imageStreamListener!;
1200 1201 1202
  }

  void _handleImageFrame(ImageInfo imageInfo, bool synchronousCall) {
1203
    setState(() {
1204
      _replaceImage(info: imageInfo);
1205
      _loadingProgress = null;
1206 1207
      _lastException = null;
      _lastStack = null;
1208 1209
      _frameNumber = _frameNumber == null ? 0 : _frameNumber! + 1;
      _wasSynchronouslyLoaded = _wasSynchronouslyLoaded | synchronousCall;
1210 1211 1212 1213 1214 1215 1216
    });
  }

  void _handleImageChunk(ImageChunkEvent event) {
    assert(widget.loadingBuilder != null);
    setState(() {
      _loadingProgress = event;
1217 1218
      _lastException = null;
      _lastStack = null;
1219 1220 1221
    });
  }

1222 1223 1224 1225 1226
  void _replaceImage({required ImageInfo? info}) {
    _imageInfo?.dispose();
    _imageInfo = info;
  }

1227
  // Updates _imageStream to newStream, and moves the stream listener
1228 1229 1230
  // registration from the old stream to the new stream (if a listener was
  // registered).
  void _updateSourceStream(ImageStream newStream) {
1231
    if (_imageStream?.key == newStream.key)
1232 1233 1234
      return;

    if (_isListeningToStream)
1235
      _imageStream!.removeListener(_getListener());
1236

1237
    if (!widget.gaplessPlayback)
1238
      setState(() { _replaceImage(info: null); });
1239

1240 1241 1242 1243 1244 1245
    setState(() {
      _loadingProgress = null;
      _frameNumber = null;
      _wasSynchronouslyLoaded = false;
    });

1246 1247
    _imageStream = newStream;
    if (_isListeningToStream)
1248
      _imageStream!.addListener(_getListener());
1249 1250 1251 1252 1253
  }

  void _listenToStream() {
    if (_isListeningToStream)
      return;
1254

1255
    _imageStream!.addListener(_getListener());
1256 1257 1258
    _completerHandle?.dispose();
    _completerHandle = null;

1259 1260 1261
    _isListeningToStream = true;
  }

1262 1263 1264 1265 1266 1267 1268 1269
  /// Stops listening to the image stream, if this state object has attached a
  /// listener.
  ///
  /// If the listener from this state is the last listener on the stream, the
  /// stream will be disposed. To keep the stream alive, set `keepStreamAlive`
  /// to true, which create [ImageStreamCompleterHandle] to keep the completer
  /// alive and is compatible with the [TickerMode] being off.
  void _stopListeningToStream({bool keepStreamAlive = false}) {
1270 1271
    if (!_isListeningToStream)
      return;
1272 1273 1274 1275 1276

    if (keepStreamAlive && _completerHandle == null && _imageStream?.completer != null) {
      _completerHandle = _imageStream!.completer!.keepAlive();
    }

1277
    _imageStream!.removeListener(_getListener());
1278 1279 1280
    _isListeningToStream = false;
  }

1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
  Widget _debugBuildErrorWidget(BuildContext context, Object error) {
    return Stack(
      alignment: Alignment.center,
      children: <Widget>[
        const Positioned.fill(
          child: Placeholder(
            color: Color(0xCF8D021F),
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(4.0),
          child: FittedBox(
            child: Text(
              '$error',
              textAlign: TextAlign.center,
              textDirection: TextDirection.ltr,
              style: const TextStyle(
                shadows: <Shadow>[
                  Shadow(blurRadius: 1.0),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

1309 1310
  @override
  Widget build(BuildContext context) {
1311 1312 1313 1314 1315
    if (_lastException != null) {
      if (widget.errorBuilder != null)
        return widget.errorBuilder!(context, _lastException!, _lastStack);
      if (kDebugMode)
        return _debugBuildErrorWidget(context, _lastException!);
1316 1317
    }

1318
    Widget result = RawImage(
1319 1320 1321 1322
      // Do not clone the image, because RawImage is a stateless wrapper.
      // The image will be disposed by this state object when it is not needed
      // anymore, such as when it is unmounted or when the image stream pushes
      // a new image.
1323
      image: _imageInfo?.image,
1324
      debugImageLabel: _imageInfo?.debugLabel,
1325 1326
      width: widget.width,
      height: widget.height,
1327
      scale: _imageInfo?.scale ?? 1.0,
1328
      color: widget.color,
1329
      colorBlendMode: widget.colorBlendMode,
1330 1331 1332
      fit: widget.fit,
      alignment: widget.alignment,
      repeat: widget.repeat,
Ian Hickson's avatar
Ian Hickson committed
1333 1334
      centerSlice: widget.centerSlice,
      matchTextDirection: widget.matchTextDirection,
1335
      invertColors: _invertColors,
1336
      isAntiAlias: widget.isAntiAlias,
1337
      filterQuality: widget.filterQuality,
1338
    );
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349

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

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

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

    return result;
1356
  }
1357 1358

  @override
1359
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
1360
    super.debugFillProperties(description);
1361 1362
    description.add(DiagnosticsProperty<ImageStream>('stream', _imageStream));
    description.add(DiagnosticsProperty<ImageInfo>('pixels', _imageInfo));
1363 1364 1365
    description.add(DiagnosticsProperty<ImageChunkEvent>('loadingProgress', _loadingProgress));
    description.add(DiagnosticsProperty<int>('frameNumber', _frameNumber));
    description.add(DiagnosticsProperty<bool>('wasSynchronouslyLoaded', _wasSynchronouslyLoaded));
1366
  }
1367
}