image.dart 50.2 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

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

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

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

35 36 37 38
// Examples can assume:
// late Widget image;
// late ImageProvider _image;

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

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

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
/// 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,
185
  int? frame,
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
  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,
225
  ImageChunkEvent? loadingProgress,
226 227
);

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

236 237
/// A widget that displays an image.
///
238 239
/// {@youtube 560 315 https://www.youtube.com/watch?v=7oIAs-0G4mw}
///
240 241 242
/// Several constructors are provided for the various ways that an image can be
/// specified:
///
243 244
///  * [Image.new], for obtaining an image from an [ImageProvider].
///  * [Image.asset], for obtaining an image from an [AssetBundle]
245
///    using a key.
246 247 248
///  * [Image.network], for obtaining an image from a URL.
///  * [Image.file], for obtaining an image from a [File].
///  * [Image.memory], for obtaining an image from a [Uint8List].
249
///
250
/// The following image formats are supported: {@macro dart.ui.imageFormats}
251
///
252 253 254 255 256 257
/// 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.
258
///
259
/// {@tool snippet}
260 261 262 263 264 265 266 267 268 269 270 271
/// 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}
///
272
/// {@tool snippet}
273 274 275 276 277 278 279 280 281 282 283
/// 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}
///
284 285 286 287 288 289 290 291 292
/// ## Memory usage
///
/// The image is stored in memory in uncompressed form (so that it can be
/// rendered). Large images will use a lot of memory: a 4K image (3840×2160)
/// will use over 30MB of RAM (assuming 32 bits per pixel).
///
/// This problem is exacerbated by the images being cached in the [ImageCache],
/// so large images can use memory for even longer than they are displayed.
///
293
/// The [Image.asset], [Image.network], [Image.file], and [Image.memory]
294 295 296 297 298 299 300 301 302 303 304
/// constructors allow a custom decode size to be specified through `cacheWidth`
/// and `cacheHeight` parameters. The engine will then decode and store the
/// image at the specified size, instead of the image's natural size.
///
/// This can significantly reduce the memory usage. For example, a 4K image that
/// will be rendered at only 384×216 pixels (one-tenth the horizontal and
/// vertical dimensions) would only use 330KB if those dimensions are specified
/// using the `cacheWidth` and `cacheHeight` parameters, a 100-fold reduction in
/// memory usage.
///
/// ### Web considerations
305 306
///
/// In the case where a network image is used on the Web platform, the
307 308 309 310
/// `cacheWidth` and `cacheHeight` parameters are only supported when the
/// application is running with the CanvasKit renderer. When the application is
/// using the HTML renderer, the web engine delegates image decoding of network
/// images to the Web, which does not support custom decode sizes.
311
///
312 313
/// See also:
///
Ian Hickson's avatar
Ian Hickson committed
314
///  * [Icon], which shows an image from a font.
315
///  * [Ink.image], which is the preferred way to show an image in a
Ian Hickson's avatar
Ian Hickson committed
316 317
///    material application (especially if the image is in a [Material] and will
///    have an [InkWell] on top of it).
318
///  * [Image](dart-ui/Image-class.html), the class in the [dart:ui] library.
319 320 321
///  * 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)
322 323 324 325
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
326
  /// [Image.network] and [Image.asset] respectively.
327
  ///
Ian Hickson's avatar
Ian Hickson committed
328 329
  /// The [image], [alignment], [repeat], and [matchTextDirection] arguments
  /// must not be null.
Ian Hickson's avatar
Ian Hickson committed
330 331 332 333 334
  ///
  /// 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.
335
  ///
336 337 338
  /// {@template flutter.widgets.image.filterQualityParameter}
  /// Use [filterQuality] to specify the rendering quality of the image.
  /// {@endtemplate}
339
  ///
340
  /// If [excludeFromSemantics] is true, then [semanticLabel] will be ignored.
341
  const Image({
342
    super.key,
343
    required this.image,
344 345
    this.frameBuilder,
    this.loadingBuilder,
346
    this.errorBuilder,
347 348
    this.semanticLabel,
    this.excludeFromSemantics = false,
349 350 351
    this.width,
    this.height,
    this.color,
352
    this.opacity,
353
    this.colorBlendMode,
354
    this.fit,
355 356
    this.alignment = Alignment.center,
    this.repeat = ImageRepeat.noRepeat,
357
    this.centerSlice,
358 359
    this.matchTextDirection = false,
    this.gaplessPlayback = false,
360
    this.isAntiAlias = false,
361
    this.filterQuality = FilterQuality.low,
362
  });
363 364 365 366

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

Ian Hickson's avatar
Ian Hickson committed
420 421 422 423
  /// 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
424 425 426 427 428
  /// 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
429 430
  /// On Android, this may require the
  /// `android.permission.READ_EXTERNAL_STORAGE` permission.
431
  ///
432
  /// {@macro flutter.widgets.image.filterQualityParameter}
433
  ///
434
  /// If [excludeFromSemantics] is true, then [semanticLabel] will be ignored.
435
  ///
436
  /// If `cacheWidth` or `cacheHeight` are provided, they indicate to the
437 438 439 440
  /// 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, {
452
    super.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.opacity,
462
    this.colorBlendMode,
Ian Hickson's avatar
Ian Hickson committed
463
    this.fit,
464 465
    this.alignment = Alignment.center,
    this.repeat = ImageRepeat.noRepeat,
Ian Hickson's avatar
Ian Hickson committed
466
    this.centerSlice,
467 468
    this.matchTextDirection = false,
    this.gaplessPlayback = false,
469
    this.isAntiAlias = false,
470
    this.filterQuality = FilterQuality.low,
471 472
    int? cacheWidth,
    int? cacheHeight,
473 474 475 476 477 478 479 480
  }) :
       // FileImage is not supported on Flutter Web therefore neither this method.
       assert(
         !kIsWeb,
         'Image.file is not supported on Flutter Web. '
         'Consider using either Image.asset or Image.network instead.',
        ),
       image = ResizeImage.resizeIfNeeded(cacheWidth, cacheHeight, FileImage(file, scale: scale)),
481
       loadingBuilder = null,
482
       assert(cacheWidth == null || cacheWidth > 0),
483
       assert(cacheHeight == null || cacheHeight > 0);
Ian Hickson's avatar
Ian Hickson committed
484

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

646 647
  /// Creates a widget that displays an [ImageStream] obtained from a [Uint8List].
  ///
648 649
  /// The `bytes` argument specifies encoded image bytes, which can be encoded
  /// in any of the following supported image formats:
650
  /// {@macro dart.ui.imageFormats}
651 652 653 654 655 656
  ///
  /// 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
657
  ///
658
  /// This only accepts compressed image formats (e.g. PNG). Uncompressed
659 660
  /// formats like rawRgba (the default format of [dart:ui.Image.toByteData])
  /// will lead to exceptions.
661
  ///
Ian Hickson's avatar
Ian Hickson committed
662 663 664 665
  /// 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.
666
  ///
667
  /// {@macro flutter.widgets.image.filterQualityParameter}
668
  ///
669
  /// If [excludeFromSemantics] is true, then [semanticLabel] will be ignored.
670
  ///
671
  /// If `cacheWidth` or `cacheHeight` are provided, they indicate to the
672 673 674 675
  /// 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
    super.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.opacity,
688
    this.colorBlendMode,
689
    this.fit,
690 691
    this.alignment = Alignment.center,
    this.repeat = ImageRepeat.noRepeat,
692
    this.centerSlice,
693 694
    this.matchTextDirection = false,
    this.gaplessPlayback = false,
695
    this.isAntiAlias = false,
696
    this.filterQuality = FilterQuality.low,
697 698
    int? cacheWidth,
    int? cacheHeight,
699
  }) : image = ResizeImage.resizeIfNeeded(cacheWidth, cacheHeight, MemoryImage(bytes, scale: scale)),
700
       loadingBuilder = null,
701
       assert(cacheWidth == null || cacheWidth > 0),
702
       assert(cacheHeight == null || cacheHeight > 0);
703

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

707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
  /// 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:
  ///
726
  /// {@template flutter.widgets.Image.frameBuilder.chainedBuildersExample}
727 728
  /// ```dart
  /// Image(
729 730
  ///   image: _image,
  ///   frameBuilder: (BuildContext context, Widget child, int? frame, bool? wasSynchronouslyLoaded) {
731
  ///     return Padding(
732
  ///       padding: const EdgeInsets.all(8.0),
733 734 735
  ///       child: child,
  ///     );
  ///   },
736
  ///   loadingBuilder: (BuildContext context, Widget child, ImageChunkEvent? loadingProgress) {
737 738 739 740 741 742 743 744 745
  ///     return Center(child: child);
  ///   },
  /// )
  /// ```
  ///
  /// In this example, the widget hierarchy will contain the following:
  ///
  /// ```dart
  /// Center(
746 747 748
  ///   child: Padding(
  ///     padding: const EdgeInsets.all(8.0),
  ///     child: image,
749
  ///   ),
750
  /// ),
751 752 753
  /// ```
  /// {@endtemplate}
  ///
754
  /// {@tool dartpad}
755 756 757 758 759 760
  /// 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.
  ///
761
  /// ** See code in examples/api/lib/widgets/image/image.frame_builder.0.dart **
762
  /// {@end-tool}
763
  final ImageFrameBuilder? frameBuilder;
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791

  /// 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:
  ///
792
  /// {@macro flutter.widgets.Image.frameBuilder.chainedBuildersExample}
793
  ///
794
  /// {@tool dartpad}
795 796 797
  /// The following sample uses [loadingBuilder] to show a
  /// [CircularProgressIndicator] while an image loads over the network.
  ///
798
  /// ** See code in examples/api/lib/widgets/image/image.loading_builder.0.dart **
799 800
  /// {@end-tool}
  ///
801 802 803
  /// 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.
804 805
  ///
  /// {@animation 400 400 https://flutter.github.io/assets-for-api-docs/assets/widgets/loading_progress_image.mp4}
806
  final ImageLoadingBuilder? loadingBuilder;
807

808 809 810 811 812 813
  /// 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.
  ///
814
  /// {@tool dartpad}
815 816 817
  /// The following sample uses [errorBuilder] to show a '😢' in place of the
  /// image that fails to load, and prints the error to the console.
  ///
818
  /// ** See code in examples/api/lib/widgets/image/image.error_builder.0.dart **
819
  /// {@end-tool}
820
  final ImageErrorWidgetBuilder? errorBuilder;
821

822 823 824 825
  /// 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
826 827 828 829 830 831
  ///
  /// 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.
832
  final double? width;
833 834 835 836 837

  /// 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
838 839 840 841 842 843
  ///
  /// 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.
844
  final double? height;
845

846
  /// If non-null, this color is blended with each image pixel using [colorBlendMode].
847
  final Color? color;
848

849 850 851 852 853 854 855 856 857 858 859 860 861 862
  /// If non-null, the value from the [Animation] is multiplied with the opacity
  /// of each image pixel before painting onto the canvas.
  ///
  /// This is more efficient than using [FadeTransition] to change the opacity
  /// of an image, since this avoids creating a new composited layer. Composited
  /// layers may double memory usage as the image is painted onto an offscreen
  /// render target.
  ///
  /// See also:
  ///
  ///  * [AlwaysStoppedAnimation], which allows you to create an [Animation]
  ///    from a single opacity value.
  final Animation<double>? opacity;

863 864
  /// The rendering quality of the image.
  ///
865
  /// {@template flutter.widgets.image.filterQuality}
866 867 868 869 870 871 872 873 874 875 876
  /// 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:
877
  ///
878 879
  ///  * [FilterQuality], the enum containing all possible filter quality
  ///    options.
880
  /// {@endtemplate}
881 882
  final FilterQuality filterQuality;

883 884 885 886 887 888 889 890
  /// 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.
891
  final BlendMode? colorBlendMode;
892

Adam Barth's avatar
Adam Barth committed
893
  /// How to inscribe the image into the space allocated during layout.
894 895 896
  ///
  /// The default varies based on the other fields. See the discussion at
  /// [paintImage].
897
  final BoxFit? fit;
898 899 900

  /// How to align the image within its bounds.
  ///
Ian Hickson's avatar
Ian Hickson committed
901
  /// The alignment aligns the given position in the image to the given position
902 903
  /// 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
904
  /// [Alignment] alignment of (1.0, 1.0) aligns the bottom right of the
Ian Hickson's avatar
Ian Hickson committed
905
  /// image with the bottom right corner of its layout bounds. Similarly, an
906
  /// alignment of (0.0, 1.0) aligns the bottom middle of the image with the
Ian Hickson's avatar
Ian Hickson committed
907 908 909 910 911 912
  /// 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
913
  /// [AlignmentDirectional]), then an ambient [Directionality] widget
Ian Hickson's avatar
Ian Hickson committed
914 915
  /// must be in scope.
  ///
916
  /// Defaults to [Alignment.center].
917 918 919 920 921 922 923
  ///
  /// See also:
  ///
  ///  * [Alignment], a class with convenient constants typically used to
  ///    specify an [AlignmentGeometry].
  ///  * [AlignmentDirectional], like [Alignment] for specifying alignments
  ///    relative to text direction.
924
  final AlignmentGeometry alignment;
925 926 927 928 929 930 931 932 933 934 935

  /// 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.
936
  final Rect? centerSlice;
937

Ian Hickson's avatar
Ian Hickson committed
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
  /// 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;

955
  /// Whether to continue showing the old image (true), or briefly show nothing
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
  /// (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.
983 984
  final bool gaplessPlayback;

985 986
  /// A Semantic description of the image.
  ///
987
  /// Used to provide a description of the image to TalkBack on Android, and
988
  /// VoiceOver on iOS.
989
  final String? semanticLabel;
990 991 992 993 994 995 996

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

997 998 999 1000 1001
  /// Whether to paint the image with anti-aliasing.
  ///
  /// Anti-aliasing alleviates the sawtooth artifact when the image is rotated.
  final bool isAntiAlias;

1002
  @override
1003
  State<Image> createState() => _ImageState();
1004 1005

  @override
1006 1007
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
1008
    properties.add(DiagnosticsProperty<ImageProvider>('image', image));
1009 1010
    properties.add(DiagnosticsProperty<Function>('frameBuilder', frameBuilder));
    properties.add(DiagnosticsProperty<Function>('loadingBuilder', loadingBuilder));
1011 1012
    properties.add(DoubleProperty('width', width, defaultValue: null));
    properties.add(DoubleProperty('height', height, defaultValue: null));
1013
    properties.add(ColorProperty('color', color, defaultValue: null));
1014
    properties.add(DiagnosticsProperty<Animation<double>?>('opacity', opacity, defaultValue: null));
1015 1016 1017 1018 1019 1020 1021 1022
    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));
1023
    properties.add(EnumProperty<FilterQuality>('filterQuality', filterQuality));
1024 1025 1026
  }
}

1027
class _ImageState extends State<Image> with WidgetsBindingObserver {
1028 1029 1030
  ImageStream? _imageStream;
  ImageInfo? _imageInfo;
  ImageChunkEvent? _loadingProgress;
1031
  bool _isListeningToStream = false;
1032 1033 1034 1035 1036 1037
  late bool _invertColors;
  int? _frameNumber;
  bool _wasSynchronouslyLoaded = false;
  late DisposableBuildContext<State<Image>> _scrollAwareContext;
  Object? _lastException;
  StackTrace? _lastStack;
1038
  ImageStreamCompleterHandle? _completerHandle;
1039 1040 1041 1042

  @override
  void initState() {
    super.initState();
1043
    WidgetsBinding.instance.addObserver(this);
1044
    _scrollAwareContext = DisposableBuildContext<State<Image>>(this);
1045 1046 1047 1048 1049
  }

  @override
  void dispose() {
    assert(_imageStream != null);
1050
    WidgetsBinding.instance.removeObserver(this);
1051
    _stopListeningToStream();
1052
    _completerHandle?.dispose();
1053
    _scrollAwareContext.dispose();
1054
    _replaceImage(info: null);
1055 1056
    super.dispose();
  }
1057 1058

  @override
1059
  void didChangeDependencies() {
1060
    _updateInvertColors();
1061
    _resolveImage();
1062

1063
    if (TickerMode.of(context)) {
1064
      _listenToStream();
1065
    } else {
1066
      _stopListeningToStream(keepStreamAlive: true);
1067
    }
1068

1069
    super.didChangeDependencies();
1070 1071
  }

1072
  @override
1073
  void didUpdateWidget(Image oldWidget) {
1074
    super.didUpdateWidget(oldWidget);
1075 1076
    if (_isListeningToStream &&
        (widget.loadingBuilder == null) != (oldWidget.loadingBuilder == null)) {
1077
      final ImageStreamListener oldListener = _getListener();
1078
      _imageStream!.addListener(_getListener(recreateListener: true));
1079
      _imageStream!.removeListener(oldListener);
1080
    }
1081
    if (widget.image != oldWidget.image) {
1082
      _resolveImage();
1083
    }
1084 1085
  }

1086 1087 1088 1089 1090 1091 1092 1093
  @override
  void didChangeAccessibilityFeatures() {
    super.didChangeAccessibilityFeatures();
    setState(() {
      _updateInvertColors();
    });
  }

1094 1095
  @override
  void reassemble() {
1096
    _resolveImage(); // in case the image cache was flushed
1097 1098 1099
    super.reassemble();
  }

1100
  void _updateInvertColors() {
1101
    _invertColors = MediaQuery.maybeInvertColorsOf(context)
1102
        ?? SemanticsBinding.instance.accessibilityFeatures.invertColors;
1103 1104
  }

1105
  void _resolveImage() {
1106
    final ScrollAwareImageProvider provider = ScrollAwareImageProvider<Object>(
1107 1108 1109
      context: _scrollAwareContext,
      imageProvider: widget.image,
    );
1110
    final ImageStream newStream =
1111
      provider.resolve(createLocalImageConfiguration(
1112
        context,
1113
        size: widget.width != null && widget.height != null ? Size(widget.width!, widget.height!) : null,
1114 1115
      ));
    _updateSourceStream(newStream);
1116 1117
  }

1118
  ImageStreamListener? _imageStreamListener;
1119 1120 1121 1122 1123 1124 1125
  ImageStreamListener _getListener({bool recreateListener = false}) {
    if(_imageStreamListener == null || recreateListener) {
      _lastException = null;
      _lastStack = null;
      _imageStreamListener = ImageStreamListener(
        _handleImageFrame,
        onChunk: widget.loadingBuilder == null ? null : _handleImageChunk,
1126 1127
        onError: widget.errorBuilder != null || kDebugMode
            ? (Object error, StackTrace? stackTrace) {
1128 1129 1130 1131
                setState(() {
                  _lastException = error;
                  _lastStack = stackTrace;
                });
1132
                assert(() {
1133 1134
                  if (widget.errorBuilder == null) {
                    // ignore: only_throw_errors, since we're just proxying the error.
1135
                    throw error; // Ensures the error message is printed to the console.
1136
                  }
1137 1138
                  return true;
                }());
1139 1140 1141 1142
              }
            : null,
      );
    }
1143
    return _imageStreamListener!;
1144 1145 1146
  }

  void _handleImageFrame(ImageInfo imageInfo, bool synchronousCall) {
1147
    setState(() {
1148
      _replaceImage(info: imageInfo);
1149
      _loadingProgress = null;
1150 1151
      _lastException = null;
      _lastStack = null;
1152 1153
      _frameNumber = _frameNumber == null ? 0 : _frameNumber! + 1;
      _wasSynchronouslyLoaded = _wasSynchronouslyLoaded | synchronousCall;
1154 1155 1156 1157 1158 1159 1160
    });
  }

  void _handleImageChunk(ImageChunkEvent event) {
    assert(widget.loadingBuilder != null);
    setState(() {
      _loadingProgress = event;
1161 1162
      _lastException = null;
      _lastStack = null;
1163 1164 1165
    });
  }

1166
  void _replaceImage({required ImageInfo? info}) {
1167 1168
    final ImageInfo? oldImageInfo = _imageInfo;
    SchedulerBinding.instance.addPostFrameCallback((_) => oldImageInfo?.dispose());
1169 1170 1171
    _imageInfo = info;
  }

1172
  // Updates _imageStream to newStream, and moves the stream listener
1173 1174 1175
  // registration from the old stream to the new stream (if a listener was
  // registered).
  void _updateSourceStream(ImageStream newStream) {
1176
    if (_imageStream?.key == newStream.key) {
1177
      return;
1178
    }
1179

1180
    if (_isListeningToStream) {
1181
      _imageStream!.removeListener(_getListener());
1182
    }
1183

1184
    if (!widget.gaplessPlayback) {
1185
      setState(() { _replaceImage(info: null); });
1186
    }
1187

1188 1189 1190 1191 1192 1193
    setState(() {
      _loadingProgress = null;
      _frameNumber = null;
      _wasSynchronouslyLoaded = false;
    });

1194
    _imageStream = newStream;
1195
    if (_isListeningToStream) {
1196
      _imageStream!.addListener(_getListener());
1197
    }
1198 1199 1200
  }

  void _listenToStream() {
1201
    if (_isListeningToStream) {
1202
      return;
1203
    }
1204

1205
    _imageStream!.addListener(_getListener());
1206 1207 1208
    _completerHandle?.dispose();
    _completerHandle = null;

1209 1210 1211
    _isListeningToStream = true;
  }

1212 1213 1214 1215 1216 1217 1218 1219
  /// 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}) {
1220
    if (!_isListeningToStream) {
1221
      return;
1222
    }
1223 1224 1225 1226 1227

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

1228
    _imageStream!.removeListener(_getListener());
1229 1230 1231
    _isListeningToStream = false;
  }

1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
  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),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

1260 1261
  @override
  Widget build(BuildContext context) {
1262
    if (_lastException != null) {
1263
      if (widget.errorBuilder != null) {
1264
        return widget.errorBuilder!(context, _lastException!, _lastStack);
1265 1266
      }
      if (kDebugMode) {
1267
        return _debugBuildErrorWidget(context, _lastException!);
1268
      }
1269 1270
    }

1271
    Widget result = RawImage(
1272 1273 1274 1275
      // 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.
1276
      image: _imageInfo?.image,
1277
      debugImageLabel: _imageInfo?.debugLabel,
1278 1279
      width: widget.width,
      height: widget.height,
1280
      scale: _imageInfo?.scale ?? 1.0,
1281
      color: widget.color,
1282
      opacity: widget.opacity,
1283
      colorBlendMode: widget.colorBlendMode,
1284 1285 1286
      fit: widget.fit,
      alignment: widget.alignment,
      repeat: widget.repeat,
Ian Hickson's avatar
Ian Hickson committed
1287 1288
      centerSlice: widget.centerSlice,
      matchTextDirection: widget.matchTextDirection,
1289
      invertColors: _invertColors,
1290
      isAntiAlias: widget.isAntiAlias,
1291
      filterQuality: widget.filterQuality,
1292
    );
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302

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

1303
    if (widget.frameBuilder != null) {
1304
      result = widget.frameBuilder!(context, result, _frameNumber, _wasSynchronouslyLoaded);
1305
    }
1306

1307
    if (widget.loadingBuilder != null) {
1308
      result = widget.loadingBuilder!(context, result, _loadingProgress);
1309
    }
1310 1311

    return result;
1312
  }
1313 1314

  @override
1315
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
1316
    super.debugFillProperties(description);
1317 1318
    description.add(DiagnosticsProperty<ImageStream>('stream', _imageStream));
    description.add(DiagnosticsProperty<ImageInfo>('pixels', _imageInfo));
1319 1320 1321
    description.add(DiagnosticsProperty<ImageChunkEvent>('loadingProgress', _loadingProgress));
    description.add(DiagnosticsProperty<int>('frameNumber', _frameNumber));
    description.add(DiagnosticsProperty<bool>('wasSynchronouslyLoaded', _wasSynchronouslyLoaded));
1322
  }
1323
}