Trending Articles       10 Flutter Listview Examples       Flutter Custom Button Example       Flutter Audio Recording       Flutter 2.0 Autocomplete TextField       Current Location Google Maps

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

Hello guys, In this post we are going to learn how we can download a file and we can show its downloading progress. 

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

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: [
                 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

 

How to Download File in Flutter

Future 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 createState() {
    // TODO: implement 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";
  double download=0.0;
  File f;

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

  Future 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: [
                 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,),
           ),
         ),
       ),
     ),
   );
  }

}

 

Read also

Download and view files inside Listview Flutter

 

 


8659 Views

Author: RRTutors

Flutter Questions

Android Questions