我遇到了一个问题,我必须从网络下载 pdf 或图像等并将它们存储在本地存储中。我正在尝试使用 GetApplicationDocumentDirectory 的路径提供程序插件,它成功存储文件但未显示在设备文件夹中。如何创建目录并存储用户可见的文件,例如图像、pdf 等。我怎样才能做到这一点。
感谢您的提前帮助
您可以通过创建文件夹来写入设备外部存储,如下面的示例代码所示
希望能帮助到你
class PDFDownloader extends StatefulWidget {
final String extension;
final String url;
final String fileName;
PDFDownloader(this.url, this.fileName,[this.extension='pdf']);
@override
_DownloadAppState createState() => new _DownloadAppState();
}
class _DownloadAppState extends State<PDFDownloader> {
bool downloading = false;
String _message;
var progressString = "";
Future<Directory> _externalDocumentsDirectory;
@override
void initState() {
//downloadFile();
checkPer();
// _bannerAd = createBannerAd()..load();
super.initState();
}
void checkPer() async {
await new Future.delayed(new Duration(seconds: 1));
bool checkResult = await SimplePermissions.checkPermission(
Permission.WriteExternalStorage);
if (!checkResult) {
var status = await SimplePermissions.requestPermission(
Permission.WriteExternalStorage);
//print("permission request result is " + resReq.toString());
if (status == PermissionStatus.authorized) {
await downloadFile();
}
} else {
await downloadFile();
}
}
@override
Widget build(BuildContext context) {
var scaffold= Scaffold(
appBar: AppBar(
title: Text("Download"),
),
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,
),
)
],
),
),
)
: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(_message ?? 'Please wait!!'),
SizedBox(
height: 10.0,
),
new RaisedButton(
textColor: Colors.white,
color: Colors.blueAccent,
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10.0)),
onPressed: () {
Navigator.pop(context);
},
child: Text('Close'),
)
],
),
),
);
return WillPopScope(
onWillPop: _onWillPop,
child: scaffold,
);
}
Future<bool> _onWillPop() {
return new Future.value(!downloading);
}
Future<void> downloadFile() async {
var dio = new Dio();
var dir = await getExternalStorageDirectory();
var knockDir =
await new Directory('${dir.path}/iLearn').create(recursive: true);
print(widget.url);
await dio.download(widget.url, '${knockDir.path}/${widget.fileName}.${widget.extension}',
onProgress: (rec, total) {
//print("Rec: $rec , Total: $total");
if (mounted) {
setState(() {
downloading = true;
progressString = ((rec / total) * 100).toStringAsFixed(0) + "%";
});
}
});
if (mounted) {
setState(() {
downloading = false;
progressString = "Completed";
_message = "File is downloaded to your SD card 'iLearn' folder!";
});
}
print("Download completed");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13601 次 |
| 最近记录: |