gpt4 book ai didi

Flutter - 如何下载视频并将它们保存到内部存储?

转载 作者:行者123 更新时间:2023-12-01 21:45:32 27 4
gpt4 key购买 nike

我正在做一个 flutter 项目,我需要实现从服务器功能下载视频。我正在考虑使用 Dio 库并将下载的视频保存到 getApplicationDocumentsDirectory() 但我还没有找不到我想要实现的示例,我尝试了一些示例并尝试修改它们,但它没有用。任何人都知道如何管理它?谢谢 。

最佳答案

您可以在下面复制粘贴运行完整代码

代码片段

Future<void> downloadFile() async {
Dio dio = Dio();

try {
var dir = await getApplicationDocumentsDirectory();
print("path ${dir.path}");
await dio.download(imgUrl, "${dir.path}/demo.mp4",
onReceiveProgress: (rec, total) {
print("Rec: $rec , Total: $total");

setState(() {
downloading = true;
progressString = ((rec / total) * 100).toStringAsFixed(0) + "%";
});
});
} catch (e) {
print(e);
}

setState(() {
downloading = false;
progressString = "Completed";
});
print("Download completed");
}

工作演示

enter image description here

输出

I/flutter (18244): path /data/user/0/yourdoamin.yourproject/app_flutter
I/flutter (18244): Rec: 2124 , Total: 2429896
I/flutter (18244): Rec: 4883 , Total: 2429896
...
I/flutter (18244): Rec: 2429896 , Total: 2429896
I/flutter (18244): Download completed

完整代码

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';

void main() => runApp(MaterialApp(
home: MyApp(),
debugShowCheckedModeBanner: false,
));

class MyApp extends StatefulWidget {
@override
MyAppState createState() {
return new MyAppState();
}
}

class MyAppState extends State<MyApp> {
final imgUrl = "https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4";
bool downloading = false;
var progressString = "";

@override
void initState() {
super.initState();

downloadFile();
}

Future<void> downloadFile() async {
Dio dio = Dio();

try {
var dir = await getApplicationDocumentsDirectory();
print("path ${dir.path}");
await dio.download(imgUrl, "${dir.path}/demo.mp4",
onReceiveProgress: (rec, total) {
print("Rec: $rec , Total: $total");

setState(() {
downloading = true;
progressString = ((rec / total) * 100).toStringAsFixed(0) + "%";
});
});
} catch (e) {
print(e);
}

setState(() {
downloading = false;
progressString = "Completed";
});
print("Download completed");
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("AppBar"),
),
body: Center(
child: downloading
? Container(
height: 120.0,
width: 200.0,
child: Card(
color: Colors.black,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(),
SizedBox(
height: 20.0,
),
Text(
"Downloading File: $progressString",
style: TextStyle(
color: Colors.white,
),
)
],
),
),
)
: Text("No Data"),
),
);
}
}

关于Flutter - 如何下载视频并将它们保存到内部存储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60761984/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com