<p>Hi, welcome back! In this tutorial, I'll show you how you can download files in your flutter app using <strong>Dio</strong> package. We are going to store the downloaded file in the ApplicationDirectory using the <strong>path_provider</strong> package.</p> <p>Before showing you the code, let me show what exactly we are going to achieve by the end of this tutorial.</p> <p>font-weight: bolder;](STEPS TO REPRODUCE:</p> <p>font-weight: bolder;](</p> <p>font-weight: bolder;](</p> <ul> <li><p>Add the package dependencies to your pubspec.yaml file</p> </li> <li><p>Use the following code in your main.dart file to achieve results as shown in the video. (Don't miss the comments in the code to understand better)</p> </li> </ul> <p>_MyHomePageState(); }</p> <p>class _MyHomePageState extends State { bool downloading = false;</p> <p>String progress = '0';</p> <p>bool isDownloaded = false;</p> <p>String uri = 'https://file-examples.com/wp-content/uploads/2017/10/file-example_PDF_1MB.pdf'; // url of the file to be downloaded</p> <p>String filename = 'test.pdf'; // file name that you desire to keep</p> <p>// downloading logic is handled by this method</p> <p downloading="true;">Future downloadFile(uri, fileName) async { setState(() );</p> <pre>String savePath = await getFilePath(fileName);
Dio dio = Dio();
dio.download( uri, savePath, onReceiveProgress: (rcv, total) { print( 'received: ${rcv.toStringAsFixed(0)} out of total: ${total.toStringAsFixed(0)}');
setState(() {
progress = ((rcv / total) * 100).toStringAsFixed(0);
});
if (progress == '100') {
setState(() {
isDownloaded = true;
});
} else if (double.parse(progress) getFilePath(uniqueFileName) async {
String path = '';
Directory dir = await getApplicationDocumentsDirectory();
path = '$/$uniqueFileName.pdf';
return path; </pre> <p>}</p> <p>@override Widget build(BuildContext context) { print('build running');</p> <pre>return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Padding( padding: const EdgeInsets.all(8.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text('$progress%'), isDownloaded ? Text( 'File Downloaded! You can see your file in the application's directory', ) : Text( 'Click the FloatingActionButton to start Downloading!'), ], ), ), ), floatingActionButton: FloatingActionButton( child: Icon(Icons.play_arrow), onPressed: () async { downloadFile(uri, filename); }), ); </pre> <p>} }`</p> <p>I hope you liked the example! Keep Fluttering and I welcome any doubts in the comments!</p>