How to fetch pdfs from local storage in flutter code example
Example: How to fetch pdfs from local storage in flutter
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';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyPDFList(),
);
}
}
class MyPDFList extends StatefulWidget{
@override
State<StatefulWidget> createState() {
return _MyPDFList();
}
}
class _MyPDFList extends State<MyPDFList>{
var files;
void getFiles() async {
List<StorageInfo> storageInfo = await PathProviderEx.getStorageInfo();
var root = storageInfo[0].rootDir;
var fm = FileManager(root: Directory(root));
files = await fm.filesTree(
excludedPaths: ["/storage/emulated/0/Android"],
extensions: ["pdf"]
);
setState(() {});
}
@override
void initState() {
getFiles();
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(
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());
}));
},
)
);
},
)
);
}
}
class ViewPDF extends StatelessWidget {
String pathPDF = "";
ViewPDF({this.pathPDF});
@override
Widget build(BuildContext context) {
return PDFViewerScaffold(
appBar: AppBar(
title: Text("Document"),
backgroundColor: Colors.deepOrangeAccent,
),
path: pathPDF
);
}
}