用Dio下载大视频导致内存不足



我正在尝试从url和视频下载视频功能的扑动应用程序预计会很大(1至2小时的720p至少)。

我使用Dio对此,但它试图将完整的视频存储在RAM中,导致内存不足错误。这是我使用的代码。

工作区吗?或者更好的解决方案?

Dio dio = Dio();
dio
.download(
url,
filePathAndName,
onReceiveProgress: (count, total) {

progressStream.add(count / total);
},
)
.asStream()
.listen((event) {

})
.onDone(() {
Fluttertoast.showToast(msg: "Video downloaded");

});

过了一会儿,它给出了这个异常:java.lang.OutOfMemoryError

由于这是一个大文件,我认为最好使用flutter_downloader插件下载您的文件,该插件还支持通知和后台模式

Init flutter downloader

WidgetsFlutterBinding.ensureInitialized();
await FlutterDownloader.initialize(
debug: true // optional: set false to disable printing logs to console
);

处理隔离

重要提示:你的UI在主隔离中呈现,而下载事件来自后台隔离(换句话说,回调中的代码在后台隔离中运行),所以你必须处理两个隔离之间的通信。例如:

ReceivePort _port = ReceivePort();
@override
void initState() {
super.initState();
IsolateNameServer.registerPortWithName(_port.sendPort, 'downloader_send_port');
_port.listen((dynamic data) {
String id = data[0];
DownloadTaskStatus status = data[1];
int progress = data[2];
setState((){ });
});
FlutterDownloader.registerCallback(downloadCallback);
}
@override
void dispose() {
IsolateNameServer.removePortNameMapping('downloader_send_port');
super.dispose();
}
static void downloadCallback(String id, DownloadTaskStatus status, int progress) {
final SendPort send = IsolateNameServer.lookupPortByName('downloader_send_port');
send.send([id, status, progress]);
}

下载文件

final taskId = await FlutterDownloader.enqueue(
url: 'your download link',
savedDir: 'the path of directory where you want to save downloaded files',
showNotification: true, // show download progress in status bar (for Android)
openFileFromNotification: true, // click on notification to open downloaded file (for Android)
);

最新更新