streamToFile function
Write the content of stream to file.
The parent directory is created if missing. The file is truncated first (FileMode.write) and flushed before the returned future completes.
On a file system without random access support (FileSystem.supportsRandomAccess is false, e.g. OPFS), the whole stream is buffered in memory and written at once with File.writeAsBytes; otherwise the stream is piped to File.openWrite.
Implementation
Future<File> streamToFile(Stream<List<int>> stream, File file) async {
final parent = file.parent;
if (!await parent.exists()) {
await parent.create(recursive: true);
}
if (!file.fs.supportsRandomAccess) {
await file.writeAsBytes(await streamToBytes(stream), flush: true);
return file;
}
final sink = file.openWrite();
try {
await sink.addStream(stream);
await sink.flush();
} catch (_) {
try {
await sink.close();
} catch (_) {
// Keep the original error
}
rethrow;
}
await sink.close();
return file;
}