@@ -29,10 +29,11 @@ class NetworkImageWithRetry extends ImageProvider<NetworkImageWithRetry> {
2929 /// Creates an object that fetches the image at the given [url] .
3030 ///
3131 /// The arguments must not be null.
32- const NetworkImageWithRetry (this .url, { this .scale = 1.0 , this .fetchStrategy = defaultFetchStrategy })
33- : assert (url != null ),
34- assert (scale != null ),
35- assert (fetchStrategy != null );
32+ const NetworkImageWithRetry (
33+ this .url, {
34+ this .scale = 1.0 ,
35+ this .fetchStrategy = defaultFetchStrategy,
36+ });
3637
3738 /// The HTTP client used to download images.
3839 static final io.HttpClient _client = io.HttpClient ();
@@ -57,10 +58,12 @@ class NetworkImageWithRetry extends ImageProvider<NetworkImageWithRetry> {
5758 /// This indirection is necessary because [defaultFetchStrategy] is used as
5859 /// the default constructor argument value, which requires that it be a const
5960 /// expression.
60- static final FetchStrategy _defaultFetchStrategyFunction = const FetchStrategyBuilder ().build ();
61+ static final FetchStrategy _defaultFetchStrategyFunction =
62+ const FetchStrategyBuilder ().build ();
6163
6264 /// The [FetchStrategy] that [NetworkImageWithRetry] uses by default.
63- static Future <FetchInstructions > defaultFetchStrategy (Uri uri, FetchFailure failure) {
65+ static Future <FetchInstructions > defaultFetchStrategy (
66+ Uri uri, FetchFailure ? failure) {
6467 return _defaultFetchStrategyFunction (uri, failure);
6568 }
6669
@@ -71,76 +74,80 @@ class NetworkImageWithRetry extends ImageProvider<NetworkImageWithRetry> {
7174
7275 @override
7376 ImageStreamCompleter load (NetworkImageWithRetry key, DecoderCallback decode) {
74- return OneFrameImageStreamCompleter (
75- _loadWithRetry (key, decode),
77+ return OneFrameImageStreamCompleter (_loadWithRetry (key, decode),
7678 informationCollector: () sync * {
77- yield ErrorDescription ('Image provider: $this ' );
78- yield ErrorDescription ('Image key: $key ' );
79- }
80- );
79+ yield ErrorDescription ('Image provider: $this ' );
80+ yield ErrorDescription ('Image key: $key ' );
81+ });
8182 }
8283
83- void _debugCheckInstructions (FetchInstructions instructions) {
84+ void _debugCheckInstructions (FetchInstructions ? instructions) {
8485 assert (() {
8586 if (instructions == null ) {
8687 if (fetchStrategy == defaultFetchStrategy) {
8788 throw StateError (
88- 'The default FetchStrategy returned null FetchInstructions. This\n '
89- 'is likely a bug in $runtimeType . Please file a bug at\n '
90- 'https://github.com/flutter/flutter/issues.'
91- );
89+ 'The default FetchStrategy returned null FetchInstructions. This\n '
90+ 'is likely a bug in $runtimeType . Please file a bug at\n '
91+ 'https://github.com/flutter/flutter/issues.' );
9292 } else {
9393 throw StateError (
94- 'The custom FetchStrategy used to fetch $url returned null\n '
95- 'FetchInstructions. FetchInstructions must never be null, but\n '
96- 'instead instruct to either make another fetch attempt or give up.'
97- );
94+ 'The custom FetchStrategy used to fetch $url returned null\n '
95+ 'FetchInstructions. FetchInstructions must never be null, but\n '
96+ 'instead instruct to either make another fetch attempt or give up.' );
9897 }
9998 }
10099 return true ;
101100 }());
102101 }
103102
104- Future <ImageInfo > _loadWithRetry (NetworkImageWithRetry key, DecoderCallback decode) async {
103+ Future <ImageInfo > _loadWithRetry (
104+ NetworkImageWithRetry key, DecoderCallback decode) async {
105105 assert (key == this );
106106
107107 final Stopwatch stopwatch = Stopwatch ()..start ();
108108 final Uri resolved = Uri .base .resolve (key.url);
109109 FetchInstructions instructions = await fetchStrategy (resolved, null );
110110 _debugCheckInstructions (instructions);
111111 int attemptCount = 0 ;
112- FetchFailure lastFailure;
112+ FetchFailure ? lastFailure;
113113
114114 while (! instructions.shouldGiveUp) {
115115 attemptCount += 1 ;
116- io.HttpClientRequest request;
116+ io.HttpClientRequest ? request;
117117 try {
118- request = await _client.getUrl (instructions.uri).timeout (instructions.timeout);
119- final io.HttpClientResponse response = await request.close ().timeout (instructions.timeout);
118+ request = await _client
119+ .getUrl (instructions.uri)
120+ .timeout (instructions.timeout);
121+ final io.HttpClientResponse response =
122+ await request.close ().timeout (instructions.timeout);
120123
121- if (response == null || response .statusCode != 200 ) {
124+ if (response.statusCode != 200 ) {
122125 throw FetchFailure ._(
123126 totalDuration: stopwatch.elapsed,
124127 attemptCount: attemptCount,
125128 httpStatusCode: response.statusCode,
126129 );
127130 }
128131
129- final _Uint8ListBuilder builder = await response.fold (
130- _Uint8ListBuilder (),
132+ final _Uint8ListBuilder builder = await response
133+ .fold (
134+ _Uint8ListBuilder (),
131135 (_Uint8ListBuilder buffer, List <int > bytes) => buffer..add (bytes),
132- ).timeout (instructions.timeout);
136+ )
137+ .timeout (instructions.timeout);
133138
134139 final Uint8List bytes = builder.data;
135140
136- if (bytes.lengthInBytes == 0 )
137- return null ;
141+ if (bytes.lengthInBytes == 0 ) {
142+ throw FetchFailure ._(
143+ totalDuration: stopwatch.elapsed,
144+ attemptCount: attemptCount,
145+ httpStatusCode: response.statusCode,
146+ );
147+ }
138148
139149 final ui.Codec codec = await decode (bytes);
140150 final ui.Image image = (await codec.getNextFrame ()).image;
141- if (image == null )
142- return null ;
143-
144151 return ImageInfo (
145152 image: image,
146153 scale: key.scale,
@@ -159,27 +166,31 @@ class NetworkImageWithRetry extends ImageProvider<NetworkImageWithRetry> {
159166 }
160167 }
161168
162- if (instructions.alternativeImage != null )
163- return instructions.alternativeImage;
169+ if (instructions.alternativeImage != null ) {
170+ return instructions.alternativeImage! ;
171+ }
164172
165173 assert (lastFailure != null );
166174
167- FlutterError .onError (FlutterErrorDetails (
168- exception: lastFailure,
169- library: 'package:flutter_image' ,
170- context: ErrorDescription ('$runtimeType failed to load ${instructions .uri }' ),
171- ));
175+ if (FlutterError .onError != null ) {
176+ FlutterError .onError !(FlutterErrorDetails (
177+ exception: lastFailure! ,
178+ library: 'package:flutter_image' ,
179+ context:
180+ ErrorDescription ('$runtimeType failed to load ${instructions .uri }' ),
181+ ));
182+ }
172183
173- return null ;
184+ throw lastFailure ! ;
174185 }
175186
176187 @override
177188 bool operator == (dynamic other) {
178- if (other.runtimeType != runtimeType)
189+ if (other.runtimeType != runtimeType) {
179190 return false ;
191+ }
180192 final NetworkImageWithRetry typedOther = other;
181- return url == typedOther.url
182- && scale == typedOther.scale;
193+ return url == typedOther.url && scale == typedOther.scale;
183194 }
184195
185196 @override
@@ -207,26 +218,26 @@ class NetworkImageWithRetry extends ImageProvider<NetworkImageWithRetry> {
207218/// [NetworkImageWithRetry] to try again.
208219///
209220/// See [NetworkImageWithRetry.defaultFetchStrategy] for an example.
210- typedef FetchStrategy = Future <FetchInstructions > Function (Uri uri, FetchFailure failure);
221+ typedef FetchStrategy = Future <FetchInstructions > Function (
222+ Uri uri, FetchFailure ? failure);
211223
212224/// Instructions [NetworkImageWithRetry] uses to fetch the image.
213225@immutable
214226class FetchInstructions {
215227 /// Instructs [NetworkImageWithRetry] to give up trying to download the image.
216228 const FetchInstructions .giveUp ({
217- @ required this .uri,
229+ required this .uri,
218230 this .alternativeImage,
219- })
220- : shouldGiveUp = true ,
221- timeout = null ;
231+ }) : shouldGiveUp = true ,
232+ timeout = Duration .zero;
222233
223234 /// Instructs [NetworkImageWithRetry] to attempt to download the image from
224235 /// the given [uri] and [timeout] if it takes too long.
225236 const FetchInstructions .attempt ({
226- @ required this .uri,
227- @ required this .timeout,
228- }) : shouldGiveUp = false ,
229- alternativeImage = null ;
237+ required this .uri,
238+ required this .timeout,
239+ }) : shouldGiveUp = false ,
240+ alternativeImage = null ;
230241
231242 /// Instructs to give up trying.
232243 ///
@@ -241,29 +252,28 @@ class FetchInstructions {
241252 final Uri uri;
242253
243254 /// Instructs to give up and use this image instead.
244- final Future <ImageInfo > alternativeImage;
255+ final Future <ImageInfo >? alternativeImage;
245256
246257 @override
247258 String toString () {
248259 return '$runtimeType (\n '
249- ' shouldGiveUp: $shouldGiveUp \n '
250- ' timeout: $timeout \n '
251- ' uri: $uri \n '
252- ' alternativeImage?: ${alternativeImage != null ? 'yes' : 'no' }\n '
253- ')' ;
260+ ' shouldGiveUp: $shouldGiveUp \n '
261+ ' timeout: $timeout \n '
262+ ' uri: $uri \n '
263+ ' alternativeImage?: ${alternativeImage != null ? 'yes' : 'no' }\n '
264+ ')' ;
254265 }
255266}
256267
257268/// Contains information about a failed attempt to fetch an image.
258269@immutable
259270class FetchFailure implements Exception {
260271 const FetchFailure ._({
261- @ required this .totalDuration,
262- @ required this .attemptCount,
272+ required this .totalDuration,
273+ required this .attemptCount,
263274 this .httpStatusCode,
264275 this .originalException,
265- }) : assert (totalDuration != null ),
266- assert (attemptCount > 0 );
276+ }) : assert (attemptCount > 0 );
267277
268278 /// The total amount of time it has taken so far to download the image.
269279 final Duration totalDuration;
@@ -276,7 +286,7 @@ class FetchFailure implements Exception {
276286 final int attemptCount;
277287
278288 /// HTTP status code, such as 500.
279- final int httpStatusCode;
289+ final int ? httpStatusCode;
280290
281291 /// The exception that caused the fetch failure.
282292 final dynamic originalException;
@@ -294,7 +304,7 @@ class FetchFailure implements Exception {
294304
295305/// An indefinitely growing builder of a [Uint8List] .
296306class _Uint8ListBuilder {
297- static const int _kInitialSize = 100000 ; // 100KB-ish
307+ static const int _kInitialSize = 100000 ; // 100KB-ish
298308
299309 int _usedLength = 0 ;
300310 Uint8List _buffer = Uint8List (_kInitialSize);
@@ -344,20 +354,16 @@ class FetchStrategyBuilder {
344354 this .maxAttempts = 5 ,
345355 this .initialPauseBetweenRetries = const Duration (seconds: 1 ),
346356 this .exponentialBackoffMultiplier = 2 ,
347- this .transientHttpStatusCodePredicate = defaultTransientHttpStatusCodePredicate,
348- }) : assert (timeout != null ),
349- assert (totalFetchTimeout != null ),
350- assert (maxAttempts != null ),
351- assert (initialPauseBetweenRetries != null ),
352- assert (exponentialBackoffMultiplier != null ),
353- assert (transientHttpStatusCodePredicate != null );
357+ this .transientHttpStatusCodePredicate =
358+ defaultTransientHttpStatusCodePredicate,
359+ });
354360
355361 /// A list of HTTP status codes that can generally be retried.
356362 ///
357363 /// You may want to use a different list depending on the needs of your
358364 /// application.
359365 static const List <int > defaultTransientHttpStatusCodes = < int > [
360- 0 , // Network error
366+ 0 , // Network error
361367 408 , // Request timeout
362368 500 , // Internal server error
363369 502 , // Bad gateway
@@ -395,7 +401,7 @@ class FetchStrategyBuilder {
395401 /// Builds a [FetchStrategy] that operates using the properties of this
396402 /// builder.
397403 FetchStrategy build () {
398- return (Uri uri, FetchFailure failure) async {
404+ return (Uri uri, FetchFailure ? failure) async {
399405 if (failure == null ) {
400406 // First attempt. Just load.
401407 return FetchInstructions .attempt (
@@ -404,18 +410,21 @@ class FetchStrategyBuilder {
404410 );
405411 }
406412
407- final bool isRetriableFailure = transientHttpStatusCodePredicate (failure.httpStatusCode) ||
413+ final bool isRetriableFailure = (failure.httpStatusCode != null &&
414+ transientHttpStatusCodePredicate (failure.httpStatusCode! )) ||
408415 failure.originalException is io.SocketException ;
409416
410417 // If cannot retry, give up.
411- if (! isRetriableFailure || // retrying will not help
412- failure.totalDuration > totalFetchTimeout || // taking too long
413- failure.attemptCount > maxAttempts) { // too many attempts
418+ if (! isRetriableFailure || // retrying will not help
419+ failure.totalDuration > totalFetchTimeout || // taking too long
420+ failure.attemptCount > maxAttempts) {
421+ // too many attempts
414422 return FetchInstructions .giveUp (uri: uri);
415423 }
416424
417425 // Exponential back-off.
418- final Duration pauseBetweenRetries = initialPauseBetweenRetries * math.pow (exponentialBackoffMultiplier, failure.attemptCount - 1 );
426+ final Duration pauseBetweenRetries = initialPauseBetweenRetries *
427+ math.pow (exponentialBackoffMultiplier, failure.attemptCount - 1 );
419428 await Future <void >.delayed (pauseBetweenRetries);
420429
421430 // Retry.
0 commit comments