factory Body()

in lib/src/body.dart [34:73]


  factory Body(body, [Encoding? encoding]) {
    if (body is Body) return body;

    Stream<List<int>> stream;
    int? contentLength;
    if (body == null) {
      contentLength = 0;
      stream = Stream.fromIterable([]);
    } else if (body is String) {
      if (encoding == null) {
        var encoded = utf8.encode(body);
        // If the text is plain ASCII, don't modify the encoding. This means
        // that an encoding of "text/plain" will stay put.
        if (!_isPlainAscii(encoded, body.length)) encoding = utf8;
        contentLength = encoded.length;
        stream = Stream.fromIterable([encoded]);
      } else {
        var encoded = encoding.encode(body);
        contentLength = encoded.length;
        stream = Stream.fromIterable([encoded]);
      }
    } else if (body is List<int>) {
      // Avoid performance overhead from an unnecessary cast.
      contentLength = body.length;
      stream = Stream.value(body);
    } else if (body is List) {
      contentLength = body.length;
      stream = Stream.value(body.cast());
    } else if (body is Stream<List<int>>) {
      // Avoid performance overhead from an unnecessary cast.
      stream = body;
    } else if (body is Stream) {
      stream = body.cast();
    } else {
      throw ArgumentError('Response body "$body" must be a String or a '
          'Stream.');
    }

    return Body._(stream, encoding, contentLength);
  }