Flutter Advanced: Download Large Files (Pdf, Json, Image etc) With Progress %

Hello guys, In this post we are going to learn how we can download a file and we can show its downloading progress. 
So we can download any file like json,pdf,image,video...

To download file and get its progress by a library called dio

So let's start 


 Step 1: Create a Flutter Project
 Step 2: pubspec.yaml file
 add below plugins into pubspec.yaml file

dev_dependencies:
  flutter_test:
    sdk: flutter
  dio: ^3.0.8
  path_provider: ^1.6.0

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: <Widget>[
                 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";
  double download=0.0;
  File f;
  
  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

Download File???

Future<void> downloadFile() async
  {
    try{

      Dio dio=Dio();
      var dir=await getApplicationDocumentsDirectory();
      f=File("${dir.path}/myimagepath.jpg");
      String fileName=imageUrl.substring(imageUrl.lastIndexOf("/")+1);
      dio.download(imageUrl, "${dir.path}/$fileName",onReceiveProgress: (rec,total){
        setState(() {
          downloading=true;
          download=(rec/total)*100;
         print(fileName);
          downloadingStr="Downloading Image : "+(download).toStringAsFixed(0);
        });


          setState(() {
            downloading=false;
            downloadingStr="Completed";

          });

      });
    }catch( e)
      {
        print(e.getMessage());
      }


  }

 

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 'dart:io';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/material.dart';

class DownloadFile extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
   return _DownloadFileState();
  }

}

class _DownloadFileState extends State<DownloadFile>
{
  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";
  double download=0.0;
  File f;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    downloadFile();
  }

  Future<void> downloadFile() async
  {
    try{

      Dio dio=Dio();
      var dir=await getApplicationDocumentsDirectory();
      f=File("${dir.path}/myimagepath.jpg");
      String fileName=imageUrl.substring(imageUrl.lastIndexOf("/")+1);
      dio.download(imageUrl, "${dir.path}/$fileName",onReceiveProgress: (rec,total){
        setState(() {
          downloading=true;
          download=(rec/total)*100;
          downloadingStr="Downloading Image : "+(download).toStringAsFixed(0);
        });


          setState(() {
            downloading=false;
            downloadingStr="Completed";

          });

      });
    }catch( e)
      {
        print(e.getMessage());
      }


  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
   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: <Widget>[
                 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,),
           ),
         ),
       ),
     ),
   );
  }

}