finalize method

Stream<List<int>> finalize()

Implementation

Stream<List<int>> finalize() {
  if (isFinalized) {
    throw StateError(
      'The FormData has already been finalized. '
      'This typically means you are using '
      'the same FormData in repeated requests.',
    );
  }
  _isFinalized = true;
  final controller = StreamController<List<int>>(sync: false);
  void writeAscii(String string) {
    controller.add(utf8.encode(string));
  }

  void writeUtf8(String string) => controller.add(utf8.encode(string));
  void writeLine() => controller.add([13, 10]); // \r\n

  for (final entry in fields) {
    writeAscii('--$boundary\r\n');
    writeAscii(_headerForField(entry.key, entry.value));
    writeUtf8(entry.value);
    writeLine();
  }

  Future.forEach<MapEntry<String, MultipartFile>>(files, (file) {
    writeAscii('--$boundary\r\n');
    writeAscii(_headerForFile(file));
    return writeStreamToSink(
      file.value.finalize(),
      controller,
    ).then((_) => writeLine());
  }).then((_) {
    writeAscii('--$boundary--\r\n');
    controller.close();
  });
  return controller.stream;
}