image.dart 50 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 13

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

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

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

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

148 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
/// 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,
182
  int? frame,
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
  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,
222
  ImageChunkEvent? loadingProgress,
223 224
);

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

233 234
/// A widget that displays an image.
///
235 236
/// {@youtube 560 315 https://www.youtube.com/watch?v=7oIAs-0G4mw}
///
237 238 239
/// Several constructors are provided for the various ways that an image can be
/// specified:
///
240 241
///  * [Image.new], for obtaining an image from an [ImageProvider].
///  * [Image.asset], for obtaining an image from an [AssetBundle]
242
///    using a key.
243 244 245
///  * [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].
246
///
247
/// The following image formats are supported: {@macro dart.ui.imageFormats}
248
///
249 250 251 252 253 254
/// 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.
255
///
256
/// {@tool snippet}
257 258 259 260 261 262 263 264 265 266 267 268
/// 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}
///
269
/// {@tool snippet}
270 271 272 273 274 275 276 277 278 279 280
/// 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}
///
281 282
/// The [Image.asset], [Image.network], [Image.file], and [Image.memory]
/// constructors allow a custom decode size to be specified through
283
/// `cacheWidth` and `cacheHeight` parameters. The engine will decode the
284 285 286 287
/// 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
288
/// `cacheWidth` and `cacheHeight` parameters are ignored as the Web engine
289 290 291
/// delegates image decoding of network images to the Web, which does not support
/// custom decode sizes.
///
292 293
/// See also:
///
Ian Hickson's avatar
Ian Hickson committed
294
///  * [Icon], which shows an image from a font.
295
///  * [Ink.image], which is the preferred way to show an image in a
Ian Hickson's avatar
Ian Hickson committed
296 297
///    material application (especially if the image is in a [Material] and will
///    have an [InkWell] on top of it).
298
///  * [Image](dart-ui/Image-class.html), the class in the [dart:ui] library.
299 300 301
///  * 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)
302 303 304 305
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
306
  /// [Image.network] and [Image.asset] respectively.
307
  ///
Ian Hickson's avatar
Ian Hickson committed
308 309
  /// The [image], [alignment], [repeat], and [matchTextDirection] arguments
  /// must not be null.
Ian Hickson's avatar
Ian Hickson committed
310 311 312 313 314
  ///
  /// 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.
315
  ///
316 317 318
  /// {@template flutter.widgets.image.filterQualityParameter}
  /// Use [filterQuality] to specify the rendering quality of the image.
  /// {@endtemplate}
319
  ///
320
  /// If [excludeFromSemantics] is true, then [semanticLabel] will be ignored.
321
  const Image({
322
    super.key,
323
    required this.image,
324 325
    this.frameBuilder,
    this.loadingBuilder,
326
    this.errorBuilder,
327 328
    this.semanticLabel,
    this.excludeFromSemantics = false,
329 330 331
    this.width,
    this.height,
    this.color,
332
    this.opacity,
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 349 350 351

  /// 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
352 353 354 355 356
  ///
  /// 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.
357 358
  ///
  /// All network images are cached regardless of HTTP headers.
Ian Hickson's avatar
Ian Hickson committed
359 360 361
  ///
  /// An optional [headers] argument can be used to send custom HTTP headers
  /// with the image request.
362
  ///
363
  /// {@macro flutter.widgets.image.filterQualityParameter}
364
  ///
365
  /// If [excludeFromSemantics] is true, then [semanticLabel] will be ignored.
366 367 368 369 370 371 372 373 374 375 376 377 378
  ///
  /// 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.
379 380
  Image.network(
    String src, {
381
    super.key,
382
    double scale = 1.0,
383 384
    this.frameBuilder,
    this.loadingBuilder,
385
    this.errorBuilder,
386 387
    this.semanticLabel,
    this.excludeFromSemantics = false,
388 389 390
    this.width,
    this.height,
    this.color,
391
    this.opacity,
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

Ian Hickson's avatar
Ian Hickson committed
412 413 414 415
  /// 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
416 417 418 419 420
  /// 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
421 422
  /// On Android, this may require the
  /// `android.permission.READ_EXTERNAL_STORAGE` permission.
423
  ///
424
  /// {@macro flutter.widgets.image.filterQualityParameter}
425
  ///
426
  /// If [excludeFromSemantics] is true, then [semanticLabel] will be ignored.
427 428 429 430 431 432
  ///
  /// 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].
433 434 435 436 437 438 439 440 441
  ///
  /// 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.
442 443
  Image.file(
    File file, {
444
    super.key,
445
    double scale = 1.0,
446
    this.frameBuilder,
447
    this.errorBuilder,
448 449
    this.semanticLabel,
    this.excludeFromSemantics = false,
Ian Hickson's avatar
Ian Hickson committed
450 451 452
    this.width,
    this.height,
    this.color,
453
    this.opacity,
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 466 467 468 469 470 471 472
  }) :
       // 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)),
473
       loadingBuilder = null,
Ian Hickson's avatar
Ian Hickson committed
474 475
       assert(alignment != null),
       assert(repeat != null),
476
       assert(filterQuality != null),
Ian Hickson's avatar
Ian Hickson committed
477
       assert(matchTextDirection != null),
478 479
       assert(cacheWidth == null || cacheWidth > 0),
       assert(cacheHeight == null || cacheHeight > 0),
480
       assert(isAntiAlias != null);
Ian Hickson's avatar
Ian Hickson committed
481

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

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

711 712 713
  /// The image to display.
  final ImageProvider image;

714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
  /// 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:
  ///
733
  /// {@template flutter.widgets.Image.frameBuilder.chainedBuildersExample}
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
  /// ```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}
  ///
761
  /// {@tool dartpad}
762 763 764 765 766 767
  /// 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.
  ///
768
  /// ** See code in examples/api/lib/widgets/image/image.frame_builder.0.dart **
769
  /// {@end-tool}
770
  final ImageFrameBuilder? frameBuilder;
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798

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

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

829 830 831 832
  /// 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
833 834 835 836 837 838
  ///
  /// 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.
839
  final double? width;
840 841 842 843 844

  /// 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
845 846 847 848 849 850
  ///
  /// 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.
851
  final double? height;
852

853
  /// If non-null, this color is blended with each image pixel using [colorBlendMode].
854
  final Color? color;
855

856 857 858 859 860 861 862 863 864 865 866 867 868 869
  /// 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;

870 871 872 873 874 875 876 877 878 879 880 881 882
  /// 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:
883
  ///
884 885
  ///  * [FilterQuality], the enum containing all possible filter quality
  ///    options.
886 887
  final FilterQuality filterQuality;

888 889 890 891 892 893 894 895
  /// 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.
896
  final BlendMode? colorBlendMode;
897

Adam Barth's avatar
Adam Barth committed
898
  /// How to inscribe the image into the space allocated during layout.
899 900 901
  ///
  /// The default varies based on the other fields. See the discussion at
  /// [paintImage].
902
  final BoxFit? fit;
903 904 905

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

  /// 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.
941
  final Rect? centerSlice;
942

Ian Hickson's avatar
Ian Hickson committed
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
  /// 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;

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

990 991
  /// A Semantic description of the image.
  ///
992
  /// Used to provide a description of the image to TalkBack on Android, and
993
  /// VoiceOver on iOS.
994
  final String? semanticLabel;
995 996 997 998 999 1000 1001

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

1002 1003 1004 1005 1006
  /// Whether to paint the image with anti-aliasing.
  ///
  /// Anti-aliasing alleviates the sawtooth artifact when the image is rotated.
  final bool isAntiAlias;

1007
  @override
1008
  State<Image> createState() => _ImageState();
1009 1010

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

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

  @override
  void initState() {
    super.initState();
1048
    WidgetsBinding.instance.addObserver(this);
1049
    _scrollAwareContext = DisposableBuildContext<State<Image>>(this);
1050 1051 1052 1053 1054
  }

  @override
  void dispose() {
    assert(_imageStream != null);
1055
    WidgetsBinding.instance.removeObserver(this);
1056
    _stopListeningToStream();
1057
    _completerHandle?.dispose();
1058
    _scrollAwareContext.dispose();
1059
    _replaceImage(info: null);
1060 1061
    super.dispose();
  }
1062 1063

  @override
1064
  void didChangeDependencies() {
1065
    _updateInvertColors();
1066
    _resolveImage();
1067 1068 1069 1070

    if (TickerMode.of(context))
      _listenToStream();
    else
1071
      _stopListeningToStream(keepStreamAlive: true);
1072

1073
    super.didChangeDependencies();
1074 1075
  }

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

1089 1090 1091 1092 1093 1094 1095 1096
  @override
  void didChangeAccessibilityFeatures() {
    super.didChangeAccessibilityFeatures();
    setState(() {
      _updateInvertColors();
    });
  }

1097 1098
  @override
  void reassemble() {
1099
    _resolveImage(); // in case the image cache was flushed
1100 1101 1102
    super.reassemble();
  }

1103
  void _updateInvertColors() {
1104
    _invertColors = MediaQuery.maybeOf(context)?.invertColors
1105
        ?? SemanticsBinding.instance.accessibilityFeatures.invertColors;
1106 1107
  }

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

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

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

  void _handleImageChunk(ImageChunkEvent event) {
    assert(widget.loadingBuilder != null);
    setState(() {
      _loadingProgress = event;
1165 1166
      _lastException = null;
      _lastStack = null;
1167 1168 1169
    });
  }

1170 1171 1172 1173 1174
  void _replaceImage({required ImageInfo? info}) {
    _imageInfo?.dispose();
    _imageInfo = info;
  }

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

    if (_isListeningToStream)
1183
      _imageStream!.removeListener(_getListener());
1184

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

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

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

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

1203
    _imageStream!.addListener(_getListener());
1204 1205 1206
    _completerHandle?.dispose();
    _completerHandle = null;

1207 1208 1209
    _isListeningToStream = true;
  }

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

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

1225
    _imageStream!.removeListener(_getListener());
1226 1227 1228
    _isListeningToStream = false;
  }

1229 1230 1231 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
  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),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

1257 1258
  @override
  Widget build(BuildContext context) {
1259 1260 1261 1262 1263
    if (_lastException != null) {
      if (widget.errorBuilder != null)
        return widget.errorBuilder!(context, _lastException!, _lastStack);
      if (kDebugMode)
        return _debugBuildErrorWidget(context, _lastException!);
1264 1265
    }

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

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

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

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

    return result;
1305
  }
1306 1307

  @override
1308
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
1309
    super.debugFillProperties(description);
1310 1311
    description.add(DiagnosticsProperty<ImageStream>('stream', _imageStream));
    description.add(DiagnosticsProperty<ImageInfo>('pixels', _imageInfo));
1312 1313 1314
    description.add(DiagnosticsProperty<ImageChunkEvent>('loadingProgress', _loadingProgress));
    description.add(DiagnosticsProperty<int>('frameNumber', _frameNumber));
    description.add(DiagnosticsProperty<bool>('wasSynchronouslyLoaded', _wasSynchronouslyLoaded));
1315
  }
1316
}