Posted in Dart Flutter

Flutter – How to list PDF files from Storage and View on Click

Flutter – How to list PDF files from Storage and View on Click Posted on May 26, 20203 Comments
I'm Hari Prasad Chaudhary from Nepal, developer of the finest educational website/app "MeroSpark" and the finest eCommerce system "PasalaY". Here I share the code snippet which I learn during development.

In this example, I have shown how to list all the PDF files from internal or external storage on the app and build a list. And whenever the user taps or pressed on it, show it on the next page. See the example below and learn how to list all PDF files from the internal storage or SD card on the app and view it when the user chooses from the list.

pdf list flutterpdf view flutter

To list and view PDF files from internal/external storage, you have to use flutter_file_manager, path, flutter_full_pdf_viewer , and path_provider_ex flutter package. Add the following lines in your pubspec.yaml file to add this package in your dependency.

dependencies:
  flutter:
    sdk: flutter
  path: ^1.6.4
  path_provider_ex: ^1.0.1
  flutter_file_manager: ^0.2.0
  flutter_full_pdf_viewer: ^1.0.6

Add dd read / write permissions in your android/app/src/main/AndroidManifest.xml before <application> tag.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

lib/main.dart: Flutter dart code, see the explanation in comment.

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_file_manager/flutter_file_manager.dart';
import 'package:flutter_full_pdf_viewer/full_pdf_viewer_scaffold.dart';
import 'package:path_provider_ex/path_provider_ex.dart';
//import package files

void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return  MaterialApp(
          home: MyPDFList(), //call MyPDF List file
    );
  }
}

//apply this class on home: attribute at MaterialApp()
class MyPDFList extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return _MyPDFList(); //create state 
  }
}

class _MyPDFList extends State<MyPDFList>{
  var files;
 
  void getFiles() async { //asyn function to get list of files
      List<StorageInfo> storageInfo = await PathProviderEx.getStorageInfo();
      var root = storageInfo[0].rootDir; //storageInfo[1] for SD card, geting the root directory
      var fm = FileManager(root: Directory(root)); //
      files = await fm.filesTree( 
        excludedPaths: ["/storage/emulated/0/Android"],
        extensions: ["pdf"] //optional, to filter files, list only pdf files
      );
      setState(() {}); //update the UI
  }

  @override
  void initState() {
    getFiles(); //call getFiles() function on initial state. 
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title:Text("PDF File list from SD Card"),
        backgroundColor: Colors.redAccent
      ),
      body:files == null? Text("Searching Files"):
           ListView.builder(  //if file/folder list is grabbed, then show here
              itemCount: files?.length ?? 0,
              itemBuilder: (context, index) {
                    return Card(
                      child:ListTile(
                         title: Text(files[index].path.split('/').last),
                         leading: Icon(Icons.picture_as_pdf),
                         trailing: Icon(Icons.arrow_forward, color: Colors.redAccent,),
                         onTap: (){
                           Navigator.push(context, MaterialPageRoute(builder: (context){
                             return ViewPDF(pathPDF:files[index].path.toString());
                             //open viewPDF page on click
                           }));
                         },
                      )
                    );
              },
          )
    );
  }
}

class ViewPDF extends StatelessWidget {
  String pathPDF = "";
  ViewPDF({this.pathPDF});

  @override
  Widget build(BuildContext context) {
    return PDFViewerScaffold( //view PDF 
        appBar: AppBar(
          title: Text("Document"),
          backgroundColor: Colors.deepOrangeAccent,
        ),
        path: pathPDF
    );
  }
}

In this way you can make your own PDF viewer, where you can list PDF files from local storage, and view when the user chooses it.

I'm Hari Prasad Chaudhary from Nepal, developer of the finest educational website/app "MeroSpark" and the finest eCommerce system "PasalaY". Here I share the code snippet which I learn during development.

3 comments

  1. Thank your very much sir it really helped me a lot but one question I didn’t understand this part:

    files = await fm.filesTree(
    excludedPaths: [“/storage/emulated/0/Android”],
    extensions: [“pdf”] //optional, to filter files, list only pdf files
    );

    what is the excludedPath used for?

    1. Thank you very much for your comment. The excludePaths is a parameter to declare about the path you want to exclude from the tree, here “/storage/emulated/0/Android” path is mentioned, this path is system path, so it is excluded, you can exclude more paths like [‘path1′,’path2’].

Leave a Reply

Your email address will not be published. Required fields are marked *