Download Files in Flutter (Pdf, Json, Image etc) With Progress : Flutter Advance

Last updated Oct 13, 2021

In this flutter example tutorial we are going to learn how to download files from url and show download progress status. For this we are using dio library which will support with null-safety.

In the most of the scenarios we get to download file from internet and store that file inside application folder/ External folder.

To download files from internet we are using the dio library. this dio library gives option to get the download progress, which means we can also show the progress of the downloading file.

Suppose we have file to download and written code for get the file, but where will store that file, and how we will store that file. To store the file inside application folder/ External folder we will use Path_provider plugin.


So we can download any file like json, pdf,image,video...

 

So let's start 


 Step 1: Create a Flutter Project
 Step 2: pubspec.yaml file
 

add below plugins into pubspec.yaml file

dependencies:
  flutter:
    sdk: flutter
  dio: ^4.0.0
  path_provider: ^2.0.2

 

Import these files into dart file

 

Step 3: Design UI elements

MaterialApp(
     theme: ThemeData(primaryColor: Colors.pink),
     home: Scaffold(
       appBar: AppBar(title: Text("Download File"),backgroundColor: Colors.pink,),
       body: Center(
         child: downloading?Container(
            height: 250,
           width: 250,
           child: Card(
             color: Colors.pink,
             child: Column(
               mainAxisAlignment: MainAxisAlignment.center,
               children: [
                 CircularProgressIndicator(backgroundColor: Colors.white,),
                 SizedBox(height: 20,),
                 Text(downloadingStr,style: TextStyle(color: Colors.white),)
               ],
             ),
           ),
         ):Container(
           child: Center(
             child: Image.file(f,height: 200,fit: BoxFit.cover,),
           ),
         ),
       ),
     ),
   )

 

 

Define required variables

var imageUrl =
    "https://www.itl.cat/pngfile/big/10-100326_desktop-wallpaper-hd-full-screen-free-download-full.jpg";
bool downloading = true;
String downloadingStr = "No data";
String savePath = "";


  
  imageUrl is our downloading file  to show downloading status we need to check the status by downloading variables   File f is the path for the downloaded file

 

How to Download File in Flutter

Future downloadFile() async {
  try {
    Dio dio = Dio();

    String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);

    savePath = await getFilePath(fileName);
   await dio.download(imageUrl, savePath, onReceiveProgress: (rec, total) {
      setState(() {
        downloading = true;
       // download = (rec / total) * 100;
        downloadingStr =
            "Downloading Image : $rec" ;

      });


    } );
    setState(() {
      downloading = false;
      downloadingStr = "Completed";
    });
  } catch (e) {
    print(e.toString());
  }
}

 

The Dio library has the method download() which require inputs of file downloading file path and path to download file
  onReceiveProgress method will return the status of downloading file
  
  While downloading the file we are updating the status by setState() method

Download File - Flutter

Download File - Flutter

Complete code

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

void main() {
  runApp(DownloadFile());
}

class DownloadFile extends StatefulWidget {
  @override
  State createState() {
    return _DownloadFileState();
  }
}

class _DownloadFileState extends State {
  var imageUrl =
      "https://www.itl.cat/pngfile/big/10-100326_desktop-wallpaper-hd-full-screen-free-download-full.jpg";
  bool downloading = true;
  String downloadingStr = "No data";
  String savePath = "";

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

  Future downloadFile() async {
    try {
      Dio dio = Dio();

      String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);

      savePath = await getFilePath(fileName);
     await dio.download(imageUrl, savePath, onReceiveProgress: (rec, total) {
        setState(() {
          downloading = true;
         // download = (rec / total) * 100;
          downloadingStr =
              "Downloading Image : $rec" ;

        });


      } );
      setState(() {
        downloading = false;
        downloadingStr = "Completed";
      });
    } catch (e) {
      print(e.toString());
    }
  }

  Future<String> getFilePath(uniqueFileName) async {
    String path = '';

    Directory dir = await getApplicationDocumentsDirectory();

    path = '${dir.path}/$uniqueFileName';

    return path;
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(primaryColor: Colors.pink),
      home: Scaffold(
        appBar: AppBar(
          title: Text("Download File"),
          backgroundColor: Colors.pink,
        ),
        body: Center(
          child: downloading
              ? Container(
                  height: 250,
                  width: 250,
                  child: Card(
                    color: Colors.pink,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        CircularProgressIndicator(
                          backgroundColor: Colors.white,
                        ),
                        SizedBox(
                          height: 20,
                        ),
                        Text(
                          downloadingStr,
                          style: TextStyle(color: Colors.white),
                        )
                      ],
                    ),
                  ),
                )
              : Container(
            height: 250,
            width: 250,
                  child: Center(
                    child: Image.file(
                      File(savePath),
                      height: 200,
                    ),
                  ),
                ),
        ),
      ),
    );
  }
}

 

Download Source code

 

Conclusion: We have covered how to download files from url and save downloaded file inside device storage location. We also covered show progress of download file status

 

Read also

Download and view files inside Listview Flutter

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

30412 Views