@@ -65,48 +65,61 @@ class RemoteImageRequest extends ImageRequest {
6565 return null ;
6666 }
6767
68- // Handle unknown content length from reverse proxy
69- final contentLength = response.contentLength;
68+ final cacheManager = this .cacheManager;
69+ final streamController = StreamController <List <int >>(sync : true );
70+ final Stream <List <int >> stream;
71+ cacheManager? .putStreamedFile (url, streamController.stream);
72+ stream = response.map ((chunk) {
73+ if (_isCancelled) {
74+ throw StateError ('Cancelled request' );
75+ }
76+ if (cacheManager != null ) {
77+ streamController.add (chunk);
78+ }
79+ return chunk;
80+ });
81+
82+ try {
83+ final Uint8List bytes = await _downloadBytes (stream, response.contentLength);
84+ streamController.close ();
85+ return await ImmutableBuffer .fromUint8List (bytes);
86+ } catch (e) {
87+ streamController.addError (e);
88+ streamController.close ();
89+ if (_isCancelled) {
90+ return null ;
91+ }
92+ rethrow ;
93+ }
94+ }
95+
96+ Future <Uint8List > _downloadBytes (Stream <List <int >> stream, int length) async {
7097 final Uint8List bytes;
7198 int offset = 0 ;
72-
73- if (contentLength >= 0 ) {
99+ if (length > 0 ) {
74100 // Known content length - use pre-allocated buffer
75- bytes = Uint8List (contentLength);
76- final subscription = response.listen ((List <int > chunk) {
77- // this is important to break the response stream if the request is cancelled
78- if (_isCancelled) {
79- throw StateError ('Cancelled request' );
80- }
101+ bytes = Uint8List (length);
102+ await stream.listen ((chunk) {
81103 bytes.setAll (offset, chunk);
82104 offset += chunk.length;
83- }, cancelOnError: true );
84- cacheManager? .putStreamedFile (url, response);
85- await subscription.asFuture ();
105+ }, cancelOnError: true ).asFuture ();
86106 } else {
87107 // Unknown content length - collect chunks dynamically
88108 final chunks = < List <int >> [];
89109 int totalLength = 0 ;
90- final subscription = response.listen ((List <int > chunk) {
91- // this is important to break the response stream if the request is cancelled
92- if (_isCancelled) {
93- throw StateError ('Cancelled request' );
94- }
110+ await stream.listen ((chunk) {
95111 chunks.add (chunk);
96112 totalLength += chunk.length;
97- }, cancelOnError: true );
98- cacheManager? .putStreamedFile (url, response);
99- await subscription.asFuture ();
113+ }, cancelOnError: true ).asFuture ();
100114
101- // Combine all chunks into a single buffer
102115 bytes = Uint8List (totalLength);
103116 for (final chunk in chunks) {
104117 bytes.setAll (offset, chunk);
105118 offset += chunk.length;
106119 }
107120 }
108121
109- return await ImmutableBuffer . fromUint8List ( bytes) ;
122+ return bytes;
110123 }
111124
112125 Future <ImageInfo ?> _loadCachedFile (
0 commit comments