finalize method Null safety

Stream<List<int>> finalize()

Implementation

Stream<List<int>> finalize() {
  if (isFinalized) {
    throw StateError("Can't finalize a finalized MultipartFile.");
  }
  _isFinalized = true;
  var 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

  fields.forEach((entry) {
    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;
}