Download Files inside Listview | View Downloaded Files Flutter

Last updated Jul 02, 2021

In this post we will learn download files from Internet and view downloaded files from the listView. To download files inside the app using Dio package. We are going to store the downloaded file in the Application Directory using the path_provider package

After downloading file to view, we are using the syncfusion_flutter_pdfviewer plugin

 

In this Post we will cover

  • Check Permissions
  • Create a Folder Directory path
  • Download file
  • View the Downloaded file

 

 

Let's get started

Step 1: Create a Flutter application

Step 2: add required dependencies in pubspec.yaml file

dependencies:
  flutter:
    sdk: flutter
  dio: ^4.0.0
  path_provider: ^2.0.2
  permission_handler :
  syncfusion_flutter_pdfviewer:
  ndialog: ^4.1.0

 

Check Permissions:

We are suing the Permission_handler plugin to check the permissions were granted or not, if permissions not granted then we are rewuesting the required permissions by below code

requestWritePermission() async {

  if (await Permission.storage.request().isGranted) {
    setState(() {
      _allowWriteFile = true;

    });
  }else
    {
      Map<Permission, PermissionStatus> statuses = await [
        Permission.storage,
      ].request();
    }

}

 

Create a Folder Directory path

To store downloaded files we are creating a folder in the storage by below code

Future<String>getDirectoryPath() async
{
  Directory appDocDirectory = await getApplicationDocumentsDirectory();

  Directory directory= await new Directory(appDocDirectory.path+'/'+'dir').create(recursive: true);

  return directory.path;
}

 

 

Download file:

Now its time to download the selected file from listview. To download file from internet we are using the dio package. The code will be like below

Future downloadFile(String url,path) async {
  if(!_allowWriteFile)
  {

    requestWritePermission();
  }
  try{
    ProgressDialog progressDialog=ProgressDialog(context,dialogTransitionType: DialogTransitionType.Bubble,title: Text("Downloading File"));

    progressDialog.show();



    await dio.download(url, path,onReceiveProgress: (rec,total){
      setState(() {
        isLoading=true;
        progress=((rec/total)*100).toStringAsFixed(0)+"%";
        progressDialog.setMessage(Text( "Dowloading $progress"));
      });

    });
    progressDialog.dismiss();

  }catch( e)
  {

    print(e.toString());
  }
}

 

View the Downloaded PDF

To view the downloaded PDF files we are using the syncfusion PDF library .

class PDFScreen extends StatelessWidget {
  String pathPDF = "";
  PDFScreen(this.pathPDF);
  final GlobalKey<SfPdfViewerState> _pdfViewerKey = GlobalKey();
  @override
  Widget build(BuildContext context) {
    return  SfPdfViewer.file(
      File(pathPDF),
      key: _pdfViewerKey,
    );
  }
}

Step 3: Update files with below code

import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:ndialog/ndialog.dart';
import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue, //primary theme color
      ),
      home: FileDownload(), //call to homepage class
    );
  }
}
class FileDownload extends StatefulWidget{
  @override
  _FileDownloadState createState() => _FileDownloadState();
}

class _FileDownloadState extends State<FileDownload> {
  late bool isLoading;
  bool _allowWriteFile=false;

  List<Course>courseContent= [];


  String progress="";
  late Dio dio;

  @override
  void initState() {

    super.initState();
    dio=Dio();
    courseContent.add(Course(title:"Chapter 2",path:"https://www.cs.purdue.edu/homes/ayg/CS251/slides/chap2.pdf"));
    courseContent.add(Course(title:"Chapter 3",path:"https://www.cs.purdue.edu/homes/ayg/CS251/slides/chap3.pdf"));
    courseContent.add(Course(title:"Chapter 4",path:"https://www.cs.purdue.edu/homes/ayg/CS251/slides/chap4.pdf"));
    courseContent.add(Course(title:"Chapter 5",path:"https://www.cs.purdue.edu/homes/ayg/CS251/slides/chap5.pdf"));
    courseContent.add(Course(title:"Chapter 6",path:"https://www.cs.purdue.edu/homes/ayg/CS251/slides/chap6.pdf"));
    courseContent.add(Course(title:"Chapter 7A",path:"https://www.cs.purdue.edu/homes/ayg/CS251/slides/chap7a.pdf"));
  }

  requestWritePermission() async {



    if (await Permission.storage.request().isGranted) {
      setState(() {

        _allowWriteFile = true;

      });
    }else
      {
        Map<Permission, PermissionStatus> statuses = await [
          Permission.storage,
        ].request();
      }


  }

  Future<String>getDirectoryPath() async
  {
    Directory appDocDirectory = await getApplicationDocumentsDirectory();

    Directory directory= await new Directory(appDocDirectory.path+'/'+'dir').create(recursive: true);

    return directory.path;
  }

  Future downloadFile(String url,path) async {
    if(!_allowWriteFile)
    {

      requestWritePermission();
    }
    try{
      ProgressDialog progressDialog=ProgressDialog(context,dialogTransitionType: DialogTransitionType.Bubble,title: Text("Downloading File"));

      progressDialog.show();



      await dio.download(url, path,onReceiveProgress: (rec,total){
        setState(() {
          isLoading=true;
          progress=((rec/total)*100).toStringAsFixed(0)+"%";
          progressDialog.setMessage(Text( "Dowloading $progress"));
        });

      });
      progressDialog.dismiss();

    }catch( e)
    {

      print(e.toString());
    }
  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      backgroundColor: Colors.white70,
      appBar: AppBar(title: Text("FIle Download"),backgroundColor: Colors.red,),
      body: Container(
        child: ListView.builder(itemBuilder: (context,index){
          String url =courseContent[index].path;
          String title =courseContent[index].title;
          String extension=url.substring(url.lastIndexOf("/"));
          return Padding(
            padding: const EdgeInsets.all(8.0),
            child: Card(
              elevation: 10,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Row(
                  mainAxisSize: MainAxisSize.max,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text("$title",style: TextStyle(fontSize: 26,color: Colors.purpleAccent,fontWeight: FontWeight.bold),),
                    RaisedButton(
                      color: Colors.green,
                      onPressed: (){
                        getDirectoryPath().then((path) {

                          File f=File(path+"$extension");
                          if(f.existsSync())
                          {
                            Navigator.push(context, MaterialPageRoute(builder: (context){
                              return PDFScreen(f.path);
                            }));
                            return;
                          }

                          downloadFile(url,"$path/$extension");
                        });

                      }, child: Text("View",style: TextStyle(fontSize: 16,color: Colors.white),),),

                  ],
                ),
              ),
            ),
          );
        },itemCount: courseContent.length,),
      ),

    );
  }
}
class PDFScreen extends StatelessWidget {
  String pathPDF = "";
  PDFScreen(this.pathPDF);
  final GlobalKey<SfPdfViewerState> _pdfViewerKey = GlobalKey();
  @override
  Widget build(BuildContext context) {
    return  SfPdfViewer.file(
      File(pathPDF),
      key: _pdfViewerKey,
    );
  }
}

class Course{
  String title;
  String path;
  Course({required this.title,required this.path});
}

 

 

 

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

9116 Views