Repository navigation
Expand file tree
/
Copy pathimage_provider.dart
More file actions
1946 lines (1824 loc) · 63.6 KB
/
Copy pathimage_provider.dart
File metadata and controls
1946 lines (1824 loc) · 63.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
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
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
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
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Examples can assume:
// late BuildContext context;
/// @docImport 'package:flutter/widgets.dart';
/// @docImport '_web_image_info_io.dart';
library;
import 'dart:async';
import 'dart:io';
import 'dart:math' as math;
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import '_network_image_io.dart'
if (dart.library.js_interop) '_network_image_web.dart'
as network_image;
import 'binding.dart';
import 'image_cache.dart';
import 'image_stream.dart';
/// Signature for the callback taken by [ImageProvider._createErrorHandlerAndKey].
typedef _KeyAndErrorHandlerCallback<T> = void Function(T key, ImageErrorListener handleError);
/// Signature used for error handling by [ImageProvider._createErrorHandlerAndKey].
typedef _AsyncKeyErrorHandler<T> = Future<void> Function(
T key,
Object exception,
StackTrace? stack,
);
/// Configuration information passed to the [ImageProvider.resolve] method to
/// select a specific image.
///
/// See also:
///
/// * [createLocalImageConfiguration], which creates an [ImageConfiguration]
/// based on ambient configuration in a [Widget] environment.
/// * [ImageProvider], which uses [ImageConfiguration] objects to determine
/// which image to obtain.
@immutable
class ImageConfiguration {
/// Creates an object holding the configuration information for an [ImageProvider].
///
/// All the arguments are optional. Configuration information is merely
/// advisory and best-effort.
const ImageConfiguration({
this.bundle,
this.devicePixelRatio,
this.locale,
this.textDirection,
this.size,
this.platform,
});
/// Creates an object holding the configuration information for an [ImageProvider].
///
/// All the arguments are optional. Configuration information is merely
/// advisory and best-effort.
ImageConfiguration copyWith({
AssetBundle? bundle,
double? devicePixelRatio,
ui.Locale? locale,
TextDirection? textDirection,
Size? size,
TargetPlatform? platform,
}) {
return ImageConfiguration(
bundle: bundle ?? this.bundle,
devicePixelRatio: devicePixelRatio ?? this.devicePixelRatio,
locale: locale ?? this.locale,
textDirection: textDirection ?? this.textDirection,
size: size ?? this.size,
platform: platform ?? this.platform,
);
}
/// The preferred [AssetBundle] to use if the [ImageProvider] needs one and
/// does not have one already selected.
final AssetBundle? bundle;
/// The device pixel ratio where the image will be shown.
final double? devicePixelRatio;
/// The language and region for which to select the image.
final ui.Locale? locale;
/// The reading direction of the language for which to select the image.
final TextDirection? textDirection;
/// The size at which the image will be rendered.
final Size? size;
/// The [TargetPlatform] for which assets should be used. This allows images
/// to be specified in a platform-neutral fashion yet use different assets on
/// different platforms, to match local conventions e.g. for color matching or
/// shadows.
final TargetPlatform? platform;
/// An image configuration that provides no additional information.
///
/// Useful when resolving an [ImageProvider] without any context.
static const ImageConfiguration empty = ImageConfiguration();
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is ImageConfiguration &&
other.bundle == bundle &&
other.devicePixelRatio == devicePixelRatio &&
other.locale == locale &&
other.textDirection == textDirection &&
other.size == size &&
other.platform == platform;
}
@override
int get hashCode => Object.hash(bundle, devicePixelRatio, locale, size, platform);
@override
String toString() {
final result = StringBuffer();
result.write('ImageConfiguration(');
var hasArguments = false;
if (bundle != null) {
result.write('bundle: $bundle');
hasArguments = true;
}
if (devicePixelRatio != null) {
if (hasArguments) {
result.write(', ');
}
result.write('devicePixelRatio: ${devicePixelRatio!.toStringAsFixed(1)}');
hasArguments = true;
}
if (locale != null) {
if (hasArguments) {
result.write(', ');
}
result.write('locale: $locale');
hasArguments = true;
}
if (textDirection != null) {
if (hasArguments) {
result.write(', ');
}
result.write('textDirection: $textDirection');
hasArguments = true;
}
if (size != null) {
if (hasArguments) {
result.write(', ');
}
result.write('size: $size');
hasArguments = true;
}
if (platform != null) {
if (hasArguments) {
result.write(', ');
}
result.write('platform: ${platform!.name}');
hasArguments = true;
}
result.write(')');
return result.toString();
}
}
/// Performs the decode process for use in [ImageProvider.loadBuffer].
///
/// This callback allows decoupling of the `cacheWidth`, `cacheHeight`, and
/// `allowUpscaling` parameters from implementations of [ImageProvider] that do
/// not expose them.
///
/// See also:
///
/// * [ResizeImage], which uses this to override the `cacheWidth`,
/// `cacheHeight`, and `allowUpscaling` parameters.
@Deprecated(
'Use ImageDecoderCallback with ImageProvider.loadImage instead. '
'This feature was deprecated after v3.7.0-1.4.pre.',
)
typedef DecoderBufferCallback = Future<ui.Codec> Function(
ui.ImmutableBuffer buffer, {
int? cacheWidth,
int? cacheHeight,
bool allowUpscaling,
});
// Method signature for _loadAsync decode callbacks.
typedef _SimpleDecoderCallback = Future<ui.Codec> Function(ui.ImmutableBuffer buffer);
/// Performs the decode process for use in [ImageProvider.loadImage].
///
/// This callback allows decoupling of the `getTargetSize` parameter from
/// implementations of [ImageProvider] that do not expose it.
///
/// See also:
///
/// * [ResizeImage], which uses this to load images at specific sizes.
typedef ImageDecoderCallback = Future<ui.Codec> Function(
ui.ImmutableBuffer buffer, {
ui.TargetImageSizeCallback? getTargetSize,
});
/// Identifies an image without committing to the precise final asset. This
/// allows a set of images to be identified and for the precise image to later
/// be resolved based on the environment, e.g. the device pixel ratio.
///
/// To obtain an [ImageStream] from an [ImageProvider], call [resolve],
/// passing it an [ImageConfiguration] object.
///
/// [ImageProvider] uses the global [imageCache] to cache images.
///
/// The type argument `T` is the type of the object used to represent a resolved
/// configuration. This is also the type used for the key in the image cache. It
/// should be immutable and implement the [==] operator and the [hashCode]
/// getter. Subclasses should subclass a variant of [ImageProvider] with an
/// explicit `T` type argument.
///
/// The type argument does not have to be specified when using the type as an
/// argument (where any image provider is acceptable).
///
/// The following image formats are supported: {@macro dart.ui.imageFormats}
///
/// ## Lifecycle of resolving an image
///
/// The [ImageProvider] goes through the following lifecycle to resolve an
/// image, once the [resolve] method is called:
///
/// 1. Create an [ImageStream] using [createStream] to return to the caller.
/// This stream will be used to communicate back to the caller when the
/// image is decoded and ready to display, or when an error occurs.
/// 2. Obtain the key for the image using [obtainKey].
/// Calling this method can throw exceptions into the zone asynchronously
/// or into the call stack synchronously. To handle that, an error handler
/// is created that catches both synchronous and asynchronous errors, to
/// make sure errors can be routed to the correct consumers.
/// The error handler is passed on to [resolveStreamForKey] and the
/// [ImageCache].
/// 3. If the key is successfully obtained, schedule resolution of the image
/// using that key. This is handled by [resolveStreamForKey]. That method
/// may fizzle if it determines the image is no longer necessary, use the
/// provided [ImageErrorListener] to report an error, set the completer
/// from the cache if possible, or call [loadImage] to fetch the encoded image
/// bytes and schedule decoding.
/// 4. The [loadImage] method is responsible for both fetching the encoded bytes
/// and decoding them using the provided [ImageDecoderCallback]. It is called
/// in a context that uses the [ImageErrorListener] to report errors back.
///
/// Subclasses normally only have to implement the [loadImage] and [obtainKey]
/// methods. A subclass that needs finer grained control over the [ImageStream]
/// type must override [createStream]. A subclass that needs finer grained
/// control over the resolution, such as delaying calling [loadImage], must override
/// [resolveStreamForKey].
///
/// The [resolve] method is marked as [nonVirtual] so that [ImageProvider]s can
/// be properly composed, and so that the base class can properly set up error
/// handling for subsequent methods.
///
/// ## Using an [ImageProvider]
///
/// {@tool snippet}
///
/// The following shows the code required to write a widget that fully conforms
/// to the [ImageProvider] and [Widget] protocols. (It is essentially a
/// bare-bones version of the [Image] widget.)
///
/// ```dart
/// class MyImage extends StatefulWidget {
/// const MyImage({
/// super.key,
/// required this.imageProvider,
/// });
///
/// final ImageProvider imageProvider;
///
/// @override
/// State<MyImage> createState() => _MyImageState();
/// }
///
/// class _MyImageState extends State<MyImage> {
/// ImageStream? _imageStream;
/// ImageInfo? _imageInfo;
///
/// @override
/// void didChangeDependencies() {
/// super.didChangeDependencies();
/// // We call _getImage here because createLocalImageConfiguration() needs to
/// // be called again if the dependencies changed, in case the changes relate
/// // to the DefaultAssetBundle, MediaQuery, etc, which that method uses.
/// _getImage();
/// }
///
/// @override
/// void didUpdateWidget(MyImage oldWidget) {
/// super.didUpdateWidget(oldWidget);
/// if (widget.imageProvider != oldWidget.imageProvider) {
/// _getImage();
/// }
/// }
///
/// void _getImage() {
/// final ImageStream? oldImageStream = _imageStream;
/// _imageStream = widget.imageProvider.resolve(createLocalImageConfiguration(context));
/// if (_imageStream!.key != oldImageStream?.key) {
/// // If the keys are the same, then we got the same image back, and so we don't
/// // need to update the listeners. If the key changed, though, we must make sure
/// // to switch our listeners to the new image stream.
/// final ImageStreamListener listener = ImageStreamListener(_updateImage);
/// oldImageStream?.removeListener(listener);
/// _imageStream!.addListener(listener);
/// }
/// }
///
/// void _updateImage(ImageInfo imageInfo, bool synchronousCall) {
/// setState(() {
/// // Trigger a build whenever the image changes.
/// _imageInfo?.dispose();
/// _imageInfo = imageInfo;
/// });
/// }
///
/// @override
/// void dispose() {
/// _imageStream?.removeListener(ImageStreamListener(_updateImage));
/// _imageInfo?.dispose();
/// _imageInfo = null;
/// super.dispose();
/// }
///
/// @override
/// Widget build(BuildContext context) {
/// return RawImage(
/// image: _imageInfo?.image, // this is a dart:ui Image object
/// scale: _imageInfo?.scale ?? 1.0,
/// );
/// }
/// }
/// ```
/// {@end-tool}
///
/// ## Creating an [ImageProvider]
///
/// {@tool sample}
/// In this example, a variant of [NetworkImage] is created that passes all the
/// [ImageConfiguration] information (locale, platform, size, etc) to the server
/// using query arguments in the image URL.
///
/// ** See code in examples/api/lib/painting/image_provider/image_provider.0.dart **
/// {@end-tool}
@optionalTypeArgs
abstract class ImageProvider<T extends Object> {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const ImageProvider();
/// Resolves this image provider using the given `configuration`, returning
/// an [ImageStream].
///
/// This is the public entry-point of the [ImageProvider] class hierarchy.
///
/// Subclasses should implement [obtainKey] and [loadImage], which are used by
/// this method. If they need to change the implementation of [ImageStream]
/// used, they should override [createStream]. If they need to manage the
/// actual resolution of the image, they should override [resolveStreamForKey].
///
/// See the Lifecycle documentation on [ImageProvider] for more information.
@nonVirtual
ImageStream resolve(ImageConfiguration configuration) {
final ImageStream stream = createStream(configuration);
// Load the key (potentially asynchronously), set up an error handling zone,
// and call resolveStreamForKey.
_createErrorHandlerAndKey(
configuration,
(T key, ImageErrorListener errorHandler) {
resolveStreamForKey(configuration, stream, key, errorHandler);
},
(T? key, Object exception, StackTrace? stack) async {
await null; // wait an event turn in case a listener has been added to the image stream.
InformationCollector? collector;
assert(() {
collector = () => <DiagnosticsNode>[
DiagnosticsProperty<ImageProvider>('Image provider', this),
DiagnosticsProperty<ImageConfiguration>('Image configuration', configuration),
DiagnosticsProperty<T>('Image key', key, defaultValue: null),
];
return true;
}());
if (stream.completer == null) {
stream.setCompleter(_ErrorImageCompleter());
}
stream.completer!.reportError(
exception: exception,
stack: stack,
context: ErrorDescription('while resolving an image'),
silent: true, // could be a network error or whatnot
informationCollector: collector,
);
},
);
return stream;
}
/// Called by [resolve] to create the [ImageStream] it returns.
///
/// Subclasses should override this instead of [resolve] if they need to
/// return some subclass of [ImageStream]. The stream created here will be
/// passed to [resolveStreamForKey].
@protected
ImageStream createStream(ImageConfiguration configuration) {
return ImageStream();
}
/// Returns the cache location for the key that this [ImageProvider] creates.
///
/// The location may be [ImageCacheStatus.untracked], indicating that this
/// image provider's key is not available in the [ImageCache].
///
/// If the `handleError` parameter is null, errors will be reported to
/// [FlutterError.onError], and the method will return null.
///
/// A completed return value of null indicates that an error has occurred.
Future<ImageCacheStatus?> obtainCacheStatus({
required ImageConfiguration configuration,
ImageErrorListener? handleError,
}) {
final completer = Completer<ImageCacheStatus?>();
_createErrorHandlerAndKey(
configuration,
(T key, ImageErrorListener innerHandleError) {
completer.complete(PaintingBinding.instance.imageCache.statusForKey(key));
},
(T? key, Object exception, StackTrace? stack) async {
if (handleError != null) {
handleError(exception, stack);
} else {
InformationCollector? collector;
assert(() {
collector = () => <DiagnosticsNode>[
DiagnosticsProperty<ImageProvider>('Image provider', this),
DiagnosticsProperty<ImageConfiguration>('Image configuration', configuration),
DiagnosticsProperty<T>('Image key', key, defaultValue: null),
];
return true;
}());
FlutterError.reportError(
FlutterErrorDetails(
context: ErrorDescription('while checking the cache location of an image'),
informationCollector: collector,
exception: exception,
stack: stack,
),
);
completer.complete();
}
},
);
return completer.future;
}
/// This method is used by both [resolve] and [obtainCacheStatus] to ensure
/// that errors thrown during key creation are handled whether synchronous or
/// asynchronous.
void _createErrorHandlerAndKey(
ImageConfiguration configuration,
_KeyAndErrorHandlerCallback<T> successCallback,
_AsyncKeyErrorHandler<T?> errorCallback,
) {
T? obtainedKey;
var didError = false;
// `handleError` does not need to be awaited because `errorCallback` will
// always eventually set the stream.completer, and external callers care only about
// when the stream completes.
@awaitNotRequired
Future<void> handleError(Object exception, StackTrace? stack) async {
if (didError) {
return;
}
if (!didError) {
didError = true;
await errorCallback(obtainedKey, exception, stack);
}
}
Future<T> key;
try {
key = obtainKey(configuration);
} catch (error, stackTrace) {
handleError(error, stackTrace);
return;
}
key
.then<void>((T key) {
obtainedKey = key;
try {
successCallback(key, handleError);
} catch (error, stackTrace) {
handleError(error, stackTrace);
}
})
.catchError(handleError);
}
/// Called by [resolve] with the key returned by [obtainKey].
///
/// Subclasses should override this method rather than calling [obtainKey] if
/// they need to use a key directly. The [resolve] method installs appropriate
/// error handling guards so that errors will bubble up to the right places in
/// the framework, and passes those guards along to this method via the
/// [handleError] parameter.
///
/// It is safe for the implementation of this method to call [handleError]
/// multiple times if multiple errors occur, or if an error is thrown both
/// synchronously into the current part of the stack and thrown into the
/// enclosing [Zone].
///
/// The default implementation uses the key to interact with the [ImageCache],
/// calling [ImageCache.putIfAbsent] and notifying listeners of the [stream].
/// Implementers that do not call super are expected to correctly use the
/// [ImageCache].
@protected
void resolveStreamForKey(
ImageConfiguration configuration,
ImageStream stream,
T key,
ImageErrorListener handleError,
) {
// This is an unusual edge case where someone has told us that they found
// the image we want before getting to this method. We should avoid calling
// load again, but still update the image cache with LRU information.
if (stream.completer != null) {
final ImageStreamCompleter? completer = PaintingBinding.instance.imageCache.putIfAbsent(
key,
() => stream.completer!,
onError: handleError,
);
assert(identical(completer, stream.completer));
return;
}
final ImageStreamCompleter? completer = PaintingBinding.instance.imageCache.putIfAbsent(
key,
() {
ImageStreamCompleter result = loadImage(
key,
PaintingBinding.instance.instantiateImageCodecWithSize,
);
// This check exists as a fallback for backwards compatibility until the
// deprecated `loadBuffer()` method is removed. Until then, ImageProvider
// subclasses may have only overridden `loadBuffer()`, in which case the
// base implementation of `loadWithSize()` will return a sentinel value
// of type `_AbstractImageStreamCompleter`.
if (result is _AbstractImageStreamCompleter) {
result = loadBuffer(key, PaintingBinding.instance.instantiateImageCodecFromBuffer);
}
return result;
},
onError: handleError,
);
if (completer != null) {
stream.setCompleter(completer);
}
}
/// Evicts an entry from the image cache.
///
/// Returns a [Future] which indicates whether the value was successfully
/// removed.
///
/// The [ImageProvider] used does not need to be the same instance that was
/// passed to an [Image] widget, but it does need to create a key which is
/// equal to one.
///
/// The [cache] is optional and defaults to the global image cache.
///
/// The [configuration] is optional and defaults to
/// [ImageConfiguration.empty].
///
/// {@tool snippet}
///
/// The following sample code shows how an image loaded using the [Image]
/// widget can be evicted using a [NetworkImage] with a matching URL.
///
/// ```dart
/// class MyWidget extends StatelessWidget {
/// const MyWidget({
/// super.key,
/// this.url = ' ... ',
/// });
///
/// final String url;
///
/// @override
/// Widget build(BuildContext context) {
/// return Image.network(url);
/// }
///
/// void evictImage() {
/// final NetworkImage provider = NetworkImage(url);
/// provider.evict().then<void>((bool success) {
/// if (success) {
/// debugPrint('removed image!');
/// }
/// });
/// }
/// }
/// ```
/// {@end-tool}
Future<bool> evict({
ImageCache? cache,
ImageConfiguration configuration = ImageConfiguration.empty,
}) async {
cache ??= imageCache;
final T key = await obtainKey(configuration);
return cache.evict(key);
}
/// Converts an [ImageProvider]'s settings plus an [ImageConfiguration] to a key
/// that describes the precise image to load.
///
/// The type of the key is determined by the subclass. It is a value that
/// unambiguously identifies the image (_including its scale_) that the
/// [loadImage] method will fetch. Different [ImageProvider]s given the same
/// constructor arguments and [ImageConfiguration] objects should return keys
/// that are '==' to each other (possibly by using a class for the key that
/// itself implements [==]).
///
/// If the result can be determined synchronously, this function should return
/// a [SynchronousFuture]. This allows image resolution to progress
/// synchronously during a frame rather than delaying image loading.
Future<T> obtainKey(ImageConfiguration configuration);
/// Converts a key into an [ImageStreamCompleter], and begins fetching the
/// image.
///
/// This method is deprecated. Implement [loadImage] instead.
///
/// The [decode] callback provides the logic to obtain the codec for the
/// image.
///
/// See also:
///
/// * [ResizeImage], for modifying the key to account for cache dimensions.
@protected
@Deprecated(
'Implement loadImage for image loading. '
'This feature was deprecated after v3.7.0-1.4.pre.',
)
ImageStreamCompleter loadBuffer(T key, DecoderBufferCallback decode) {
return _AbstractImageStreamCompleter();
}
/// Converts a key into an [ImageStreamCompleter], and begins fetching the
/// image.
///
/// For backwards-compatibility the default implementation of this method returns
/// an object that will cause [resolveStreamForKey] to consult [loadBuffer].
/// However, implementors of this interface should only override this method
/// and not [loadBuffer], which is deprecated.
///
/// The [decode] callback provides the logic to obtain the codec for the
/// image.
///
/// See also:
///
/// * [ResizeImage], for modifying the key to account for cache dimensions.
// TODO(tvolkert): make abstract (https://github.com/flutter/flutter/issues/119209)
@protected
ImageStreamCompleter loadImage(T key, ImageDecoderCallback decode) {
return _AbstractImageStreamCompleter();
}
@override
String toString() => '${objectRuntimeType(this, 'ImageConfiguration')}()';
}
/// A class that exists to facilitate backwards compatibility in the transition
/// from [ImageProvider.loadBuffer] to [ImageProvider.loadImage]
class _AbstractImageStreamCompleter extends ImageStreamCompleter {}
/// Key for the image obtained by an [AssetImage] or [ExactAssetImage].
///
/// This is used to identify the precise resource in the [imageCache].
@immutable
class AssetBundleImageKey {
/// Creates the key for an [AssetImage] or [AssetBundleImageProvider].
const AssetBundleImageKey({required this.bundle, required this.name, required this.scale});
/// The bundle from which the image will be obtained.
///
/// The image is obtained by calling [AssetBundle.load] on the given [bundle]
/// using the key given by [name].
final AssetBundle bundle;
/// The key to use to obtain the resource from the [bundle]. This is the
/// argument passed to [AssetBundle.load].
final String name;
/// The scale to place in the [ImageInfo] object of the image.
final double scale;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is AssetBundleImageKey &&
other.bundle == bundle &&
other.name == name &&
other.scale == scale;
}
@override
int get hashCode => Object.hash(bundle, name, scale);
@override
String toString() =>
'${objectRuntimeType(this, 'AssetBundleImageKey')}(bundle: $bundle, name: "$name", scale: $scale)';
}
/// A subclass of [ImageProvider] that knows about [AssetBundle]s.
///
/// This factors out the common logic of [AssetBundle]-based [ImageProvider]
/// classes, simplifying what subclasses must implement to just [obtainKey].
abstract class AssetBundleImageProvider extends ImageProvider<AssetBundleImageKey> {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const AssetBundleImageProvider();
@override
ImageStreamCompleter loadImage(AssetBundleImageKey key, ImageDecoderCallback decode) {
InformationCollector? collector;
assert(() {
collector = () => <DiagnosticsNode>[
DiagnosticsProperty<ImageProvider>('Image provider', this),
DiagnosticsProperty<AssetBundleImageKey>('Image key', key),
];
return true;
}());
return MultiFrameImageStreamCompleter(
codec: _loadAsync(key, decode: decode),
scale: key.scale,
debugLabel: key.name,
informationCollector: collector,
);
}
/// Converts a key into an [ImageStreamCompleter], and begins fetching the
/// image.
@override
ImageStreamCompleter loadBuffer(AssetBundleImageKey key, DecoderBufferCallback decode) {
InformationCollector? collector;
assert(() {
collector = () => <DiagnosticsNode>[
DiagnosticsProperty<ImageProvider>('Image provider', this),
DiagnosticsProperty<AssetBundleImageKey>('Image key', key),
];
return true;
}());
return MultiFrameImageStreamCompleter(
codec: _loadAsync(key, decode: decode),
scale: key.scale,
debugLabel: key.name,
informationCollector: collector,
);
}
/// Fetches the image from the asset bundle, decodes it, and returns a
/// corresponding [ImageInfo] object.
///
/// This function is used by [loadImage].
@protected
Future<ui.Codec> _loadAsync(
AssetBundleImageKey key, {
required _SimpleDecoderCallback decode,
}) async {
final ui.ImmutableBuffer buffer;
// Hot reload/restart could change whether an asset bundle or key in a
// bundle are available, or if it is a network backed bundle.
try {
buffer = await key.bundle.loadBuffer(key.name);
} on FlutterError {
PaintingBinding.instance.imageCache.evict(key);
rethrow;
}
return decode(buffer);
}
}
/// Key used internally by [ResizeImage].
///
/// This is used to identify the precise resource in the [imageCache].
@immutable
class ResizeImageKey {
// Private constructor so nobody from the outside can poison the image cache
// with this key. It's only accessible to [ResizeImage] internally.
const ResizeImageKey._(
this._providerCacheKey,
this._policy,
this._width,
this._height,
this._allowUpscaling,
);
final Object _providerCacheKey;
final ResizeImagePolicy _policy;
final int? _width;
final int? _height;
final bool _allowUpscaling;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is ResizeImageKey &&
other._providerCacheKey == _providerCacheKey &&
other._policy == _policy &&
other._width == _width &&
other._height == _height &&
other._allowUpscaling == _allowUpscaling;
}
@override
int get hashCode => Object.hash(_providerCacheKey, _policy, _width, _height, _allowUpscaling);
}
/// Configures the behavior for [ResizeImage].
///
/// This is used in [ResizeImage.policy] to affect how the [ResizeImage.width]
/// and [ResizeImage.height] properties are interpreted.
enum ResizeImagePolicy {
/// Sizes the image to the exact width and height specified by
/// [ResizeImage.width] and [ResizeImage.height].
///
/// If [ResizeImage.width] and [ResizeImage.height] are both non-null, the
/// output image will have the specified width and height (with the
/// corresponding aspect ratio) regardless of whether it matches the source
/// image's intrinsic aspect ratio. This case is similar to [BoxFit.fill].
///
/// If only one of `width` and `height` is non-null, then the output image
/// will be scaled to the associated width or height, and the other dimension
/// will take whatever value is needed to maintain the image's original aspect
/// ratio. These cases are similar to [BoxFit.fitWidth] and
/// [BoxFit.fitHeight], respectively.
///
/// If [ResizeImage.allowUpscaling] is false (the default), the width and the
/// height of the output image will each be clamped to the intrinsic width and
/// height of the image. This may result in a different aspect ratio than the
/// aspect ratio specified by the target width and height (e.g. if the height
/// gets clamped downwards but the width does not).
///
/// ## Examples
///
/// The examples below show how [ResizeImagePolicy.exact] works in various
/// scenarios. In each example, the source image has a size of 300x200
/// (landscape orientation), the red box is a 150x150 square, and the green
/// box is a 400x400 square.
///
/// <table>
/// <tr>
/// <td>Scenario</td>
/// <td>Output</td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// width: 150,
/// height: 150,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// width: 150,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// height: 150,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// width: 400,
/// height: 400,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// width: 400,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// height: 400,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// width: 400,
/// height: 400,
/// allowUpscaling: true,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),