_network_image_io.dart 5.76 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6 7 8 9 10
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
import 'dart:io';
import 'dart:ui' as ui;

import 'package:flutter/foundation.dart';

11
import 'binding.dart';
12 13 14 15
import 'debug.dart';
import 'image_provider.dart' as image_provider;
import 'image_stream.dart';

16
/// The dart:io implementation of [image_provider.NetworkImage].
17
@immutable
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
class NetworkImage extends image_provider.ImageProvider<image_provider.NetworkImage> implements image_provider.NetworkImage {
  /// Creates an object that fetches the image at the given URL.
  ///
  /// The arguments [url] and [scale] must not be null.
  const NetworkImage(this.url, { this.scale = 1.0, this.headers })
    : assert(url != null),
      assert(scale != null);

  @override
  final String url;

  @override
  final double scale;

  @override
33
  final Map<String, String>? headers;
34 35 36 37 38 39 40

  @override
  Future<NetworkImage> obtainKey(image_provider.ImageConfiguration configuration) {
    return SynchronousFuture<NetworkImage>(this);
  }

  @override
41
  ImageStreamCompleter load(image_provider.NetworkImage key, image_provider.DecoderCallback decode) {
42 43 44
    // Ownership of this controller is handed off to [_loadAsync]; it is that
    // method's responsibility to close the controller's stream when the image
    // has been loaded or an error is thrown.
45 46 47
    final StreamController<ImageChunkEvent> chunkEvents = StreamController<ImageChunkEvent>();

    return MultiFrameImageStreamCompleter(
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
      codec: _loadAsync(key as NetworkImage, chunkEvents, null, decode),
      chunkEvents: chunkEvents.stream,
      scale: key.scale,
      debugLabel: key.url,
      informationCollector: () => <DiagnosticsNode>[
        DiagnosticsProperty<image_provider.ImageProvider>('Image provider', this),
        DiagnosticsProperty<image_provider.NetworkImage>('Image key', key),
      ],
    );
  }

  @override
  ImageStreamCompleter loadBuffer(image_provider.NetworkImage key, image_provider.DecoderBufferCallback decode) {
    // Ownership of this controller is handed off to [_loadAsync]; it is that
    // method's responsibility to close the controller's stream when the image
    // has been loaded or an error is thrown.
    final StreamController<ImageChunkEvent> chunkEvents = StreamController<ImageChunkEvent>();

    return MultiFrameImageStreamCompleter(
      codec: _loadAsync(key as NetworkImage, chunkEvents, decode, null),
68 69
      chunkEvents: chunkEvents.stream,
      scale: key.scale,
70
      debugLabel: key.url,
71 72 73 74
      informationCollector: () => <DiagnosticsNode>[
        DiagnosticsProperty<image_provider.ImageProvider>('Image provider', this),
        DiagnosticsProperty<image_provider.NetworkImage>('Image key', key),
      ],
75 76 77
    );
  }

78 79 80 81 82 83 84 85 86
  // Do not access this field directly; use [_httpClient] instead.
  // We set `autoUncompress` to false to ensure that we can trust the value of
  // the `Content-Length` HTTP header. We automatically uncompress the content
  // in our call to [consolidateHttpClientResponseBytes].
  static final HttpClient _sharedHttpClient = HttpClient()..autoUncompress = false;

  static HttpClient get _httpClient {
    HttpClient client = _sharedHttpClient;
    assert(() {
87
      if (debugNetworkImageHttpClientProvider != null) {
88
        client = debugNetworkImageHttpClientProvider!();
89
      }
90 91 92 93
      return true;
    }());
    return client;
  }
94 95 96 97

  Future<ui.Codec> _loadAsync(
    NetworkImage key,
    StreamController<ImageChunkEvent> chunkEvents,
98 99
    image_provider.DecoderBufferCallback? decode,
    image_provider.DecoderCallback? decodeDepreacted,
100 101 102 103 104
  ) async {
    try {
      assert(key == this);

      final Uri resolved = Uri.base.resolve(key.url);
105

106
      final HttpClientRequest request = await _httpClient.getUrl(resolved);
107

108 109
      headers?.forEach((String name, String value) {
        request.headers.add(name, value);
110
      });
111
      final HttpClientResponse response = await request.close();
112 113 114 115
      if (response.statusCode != HttpStatus.ok) {
        // The network may be only temporarily unavailable, or the file will be
        // added on the server later. Avoid having future calls to resolve
        // fail to check the network again.
116
        await response.drain<List<int>>(<int>[]);
117
        throw image_provider.NetworkImageLoadException(statusCode: response.statusCode, uri: resolved);
118
      }
119

120 121
      final Uint8List bytes = await consolidateHttpClientResponseBytes(
        response,
122
        onBytesReceived: (int cumulative, int? total) {
123 124 125 126 127
          chunkEvents.add(ImageChunkEvent(
            cumulativeBytesLoaded: cumulative,
            expectedTotalBytes: total,
          ));
        },
128
      );
129
      if (bytes.lengthInBytes == 0) {
130
        throw Exception('NetworkImage is an empty file: $resolved');
131
      }
132

133 134 135 136 137 138 139
      if (decode != null) {
        final ui.ImmutableBuffer buffer = await ui.ImmutableBuffer.fromUint8List(bytes);
        return decode(buffer);
      } else {
        assert(decodeDepreacted != null);
        return decodeDepreacted!(bytes);
      }
140 141 142 143 144
    } catch (e) {
      // Depending on where the exception was thrown, the image cache may not
      // have had a chance to track the key in the cache at all.
      // Schedule a microtask to give the cache a chance to add the key.
      scheduleMicrotask(() {
145
        PaintingBinding.instance.imageCache.evict(key);
146 147
      });
      rethrow;
148 149 150 151 152 153
    } finally {
      chunkEvents.close();
    }
  }

  @override
154
  bool operator ==(Object other) {
155
    if (other.runtimeType != runtimeType) {
156
      return false;
157
    }
158 159 160
    return other is NetworkImage
        && other.url == url
        && other.scale == scale;
161 162 163
  }

  @override
164
  int get hashCode => Object.hash(url, scale);
165 166

  @override
167
  String toString() => '${objectRuntimeType(this, 'NetworkImage')}("$url", scale: $scale)';
168
}