I'm currently facing an issue, where I'm trying to Save a large video file (586 Mb). I'm able to download the entire file but, when I try to write this file to memory, I get an Error of “Out of memory”. It works for smaller video files like (80mb, 100 mb) but fails for the large files. I'm attaching the code snippet for reference.
Future download() async {
var request = http.Request('GET', Uri.parse(url!));
var response = httpClient.send(request).timeout(Duration(seconds: 3));
var chunks = <List<int>>[];
var downloaded = 0;
try{
response.asStream().listen((http.StreamedResponse r) {
if(r.statusCode==HttpStatus.ok){
r.stream.listen((List<int> chunk) {
// Display percentage of completion
chunks.add(chunk);
downloaded += chunk.length;
downloadingCallBack(downloaded / r.contentLength! * 100,filesize(downloaded),filesize(r.contentLength));
}, onDone: () async {
// Display percentage of completion
print('downloadPercentage: ${downloaded / r.contentLength! * 100}');
// Save the file
try{
var file = File('$dirPath/$fileName');
//The Uint8List below throws the error "Out of memory and I'm not able to write the file to memory"
***Error Here ==>*** final bytes = Uint8List(r.contentLength!); //Code fails here, (r.contentLength is 586900112 bytes)
var offset = 0;
for (var chunk in chunks) {
bytes.setRange(offset, offset + chunk.length, chunk);
offset += chunk.length;
}
await file.writeAsBytes(bytes);
downloadingDoneBack(true);
return;
}catch(fileException){
rethrow;
}finally{
httpClient.close();
}
});
}else{
downloadingDoneBack(false);
}
});
}catch(e){
downloadingDoneBack(false);
}finally{
httpClient.close();
}
}