Reputation: 103
I was struct in a problem that i have to download pdf or images etc from network and store them in local storage.i am trying path provider plugin with GetApplicationDocumentDirectory its successfully storing files but not showing in device folder. how to create a directory and store files such as images pdfs etc that are visible to users. how could i achieve that.
thanks for help in advance
Upvotes: 6
Views: 14050
Reputation: 71
To create a Directory of App in Internal Storage use this snippet:
Directory directory = await getExternalStorageDirectory();
String fileName =
"xyz.pdf";
String newPath = "";
print(directory);
List<String> paths = directory.path.split("/");
for (int x = 1; x < paths.length; x++) {
String folder = paths[x];
if (folder != "Android") {
newPath += "/" + folder;
} else {
break;
}
}
newPath = newPath + "/YourAppName";
directory = Directory(newPath);
if (!await directory.exists()) {
await directory.create(recursive: true);
}
if (await directory.exists()) {
final File file = File(directory.path + "/$fileName");
// your logic for saving the file.
}
For a Detailed Explanation check out this Medium Article by Retroportal Studio: https://retroportalstudio.medium.com/saving-files-to-application-folder-and-gallery-in-flutter-e9be2ebee92a
Upvotes: 1
Reputation: 9933
You can write to the device external storage as shown in the below example code by creating the folder
Hope it helps
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");
}
}
Upvotes: 4