Error opening PDF file after downloading from server Flutter - flutter

Hello I have a screen in the app that downloads a PDF file and displays the download progress in percent. After downloading, the file is opened using the package of pdf_render: ^ 1.0.10. Sometimes it opens and displays the PDF file and sometimes it does not open the file and I have a blank screen. I have no fault in the console and I do not know what the fault is. Thank you
Flutter App :
class Web_view_vehicle extends StatefulWidget {
var choice ;
var name_vehicle;
Web_view_vehicle({ required this.choice , this.name_vehicle}) : super();
#override
_Web_view_vehicleState createState() => _Web_view_vehicleState();
}
class _Web_view_vehicleState extends State<Web_view_vehicle> {
bool downloading = false;
String progressString = "";
String path = '';
late List data ;
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/teste.pdf');
}
Future<File> writeCounter(Uint8List stream) async {
final file = await _localFile;
// Write the file
return file.writeAsBytes(stream);
}
Future<Uint8List> fetchPost() async {
Dio dio = Dio();
var response = await dio.get(widget.choice,
onReceiveProgress: (rec, total) {
print("Rec: $rec , Total: $total");
if(!mounted)return;
setState(() {
downloading = true;
progressString = ((rec / total) * 100).toStringAsFixed(0) + "%";
});
},options: Options(responseType: ResponseType.bytes));
final responseJson = response.data;
if (!mounted) {
}
setState(() {
downloading = false;
progressString = "Completed";
});
print("Download completed");
return responseJson;
}
loadPdf() async {
writeCounter((await fetchPost()));
path = (await _localFile).path;
if (!mounted) return;
setState(() {});
}
#override
void initState() {
super.initState();
loadPdf();
}
#override
Widget build(BuildContext context) {
Color? bgColor = Colors.grey[300];
return Scaffold(
backgroundColor: bgColor,
appBar: AppBar(
leading: Padding(
padding: const EdgeInsets.fromLTRB(5.0 , 0.0 , 0.0 , 0.0),
child: new IconButton(
icon: new Icon(Icons.arrow_back),
onPressed: (){Navigator.pop(context,true);}
),
),
title: Text('מדריך לרכב ${widget.name_vehicle}',textAlign: TextAlign.center,textDirection: TextDirection.rtl,),
backgroundColor: Colors.red[400],
centerTitle: true,
actions: <Widget>[
],
),
body:
(path.length > 5)?
PdfViewer.openFile(path,
):
Center(child: Column(crossAxisAlignment: CrossAxisAlignment.center,mainAxisAlignment: MainAxisAlignment.center,mainAxisSize: MainAxisSize.max,
children: [
CircularProgressIndicator(),
Text('טוען מדריך ${progressString}',textDirection: TextDirection.rtl,textAlign: TextAlign.center,)
],
))
);
}
}

Related

how to automatically trigger record

I have a audio recording page which starts when I tap in the button and stop when i tap the button once again
import 'package:flutter_sound/flutter_sound.dart';
import 'package:permission_handler/permission_handler.dart';
class AudioWidget extends StatefulWidget {
#override
State<AudioWidget> createState() => _AudioWidgetState();
}
``class _AudioWidgetState extends State<AudioWidget> {
final FirebaseAuth _auth = FirebaseAuth.instance;
String AudioUrl = '';
final recorder = FlutterSoundRecorder();
bool isRecorderReady = false;
#override
void initState() {
super.initState();
initRecorder();
record();
}
#override
void dispose() {
recorder.closeRecorder();
super.dispose();
}
Future initRecorder() async {
final status = await Permission.microphone.request();
if (status != PermissionStatus.granted) {
throw 'Microphone permission not granted';
}
await recorder.openRecorder();
isRecorderReady = true;
recorder.setSubscriptionDuration(const Duration(milliseconds: 500));
}
Future record() async {
if (!isRecorderReady) {
return;
}
await recorder.startRecorder(toFile: 'audio');
}
Future stop() async {
if (!isRecorderReady) {
return;
}
final path = await recorder.stopRecorder();
final audioFile = File(path!);
print('Recorder audio: $audioFile');
final ref = FirebaseStorage.instance
.ref()
.child('Audio')
.child(DateTime.now().toIso8601String() + ".mp3");
await ref.putData(audioFile.readAsBytesSync());
AudioUrl = await ref.getDownloadURL();
FirebaseFirestore.instance.collection('Audio').add({
'AudioUrl': AudioUrl,
'userId': _auth.currentUser!.email,
'createdAt': DateTime.now(),
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Audio"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
StreamBuilder<RecordingDisposition>(
stream: recorder.onProgress,
builder: (context, snapshot) {
final duration = snapshot.hasData
? snapshot.data!.duration
: Duration.zero;
String twoDigits(int n) => n.toString().padLeft(2, '0');
final twoDigitMinutes =
twoDigits(duration.inMinutes.remainder(60));
final twoDigitSeconds =
twoDigits(duration.inSeconds.remainder(60));
if (twoDigitSeconds ==
FFAppState().AudioMaxDuration.toString()) {
stop();
}
return Text('$twoDigitMinutes:$twoDigitSeconds',
style: const TextStyle(
fontSize: 80,
fontWeight: FontWeight.bold,
));
}),
const SizedBox(height: 32),
ElevatedButton(
child: Icon(
recorder.isRecording ? Icons.stop : Icons.mic,
size: 80,
),
onPressed: () async {
if (recorder.isRecording) {
await stop();
context.pop();
} else {
await record();
}
setState(() {});
},
),
],
)),
),
);
}
}
how can I automatically start recording once I open the audio recording page and tap it to stop and tap again to start?
I tried to put the record function in initstate but it didn't work
void initState() {
super.initState();
initRecorder();
record();
}

Flutter download audio zip file and play in application

Hello friend i am new in flutter i need help i have project where almost different zip file hosted on sever every zip file have different audio with categories now i want if user want to download that zip file and extract audio then able to play in application it not visible in phone memory ?here example of code but this is for images and one zip file i take code from this url
https://www.coderzheaven.com/2019/06/07/download-zip-extract-it-and-show-the-images-file-in-list-in-ui/
here my code
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:archive/archive.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
class DownloadAssetsDemo extends StatefulWidget {
DownloadAssetsDemo() : super();
final String title = "Download & Extract ZIP Demo";
#override
DownloadAssetsDemoState createState() => DownloadAssetsDemoState();
}
class DownloadAssetsDemoState extends State<DownloadAssetsDemo> {
//
bool _downloading;
String _dir;
List<String> _images, _tempImages;
String _zipPath = 'https://coderzheaven.com/youtube_flutter/images.zip';
String _localZipFileName = 'images.zip';
#override
void initState() {
super.initState();
_images = List();
_tempImages = List();
_downloading = false;
_initDir();
}
_initDir() async {
if (null == _dir) {
_dir = (await getApplicationDocumentsDirectory()).path;
}
}
Future<File> _downloadFile(String url, String fileName) async {
var req = await http.Client().get(Uri.parse(url));
var file = File('$_dir/$fileName');
return file.writeAsBytes(req.bodyBytes);
}
Future<void> _downloadZip() async {
setState(() {
_downloading = true;
});
_images.clear();
_tempImages.clear();
var zippedFile = await _downloadFile(_zipPath, _localZipFileName);
await unarchiveAndSave(zippedFile);
setState(() {
_images.addAll(_tempImages);
_downloading = false;
});
}
unarchiveAndSave(var zippedFile) async {
var bytes = zippedFile.readAsBytesSync();
var archive = ZipDecoder().decodeBytes(bytes);
for (var file in archive) {
var fileName = '$_dir/${file.name}';
if (file.isFile) {
var outFile = File(fileName);
//print('File:: ' + outFile.path);
_tempImages.add(outFile.path);
outFile = await outFile.create(recursive: true);
await outFile.writeAsBytes(file.content);
}
}
}
buildList() {
return Expanded(
child: ListView.builder(
itemCount: _images.length,
itemBuilder: (BuildContext context, int index) {
return Image.file(
File(_images[index]),
fit: BoxFit.fitWidth,
);
},
),
);
}
progress() {
return Container(
width: 25,
height: 25,
padding: EdgeInsets.fromLTRB(0.0, 20.0, 10.0, 20.0),
child: CircularProgressIndicator(
strokeWidth: 3.0,
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
actions: <Widget>[
_downloading ? progress() : Container(),
IconButton(
icon: Icon(Icons.file_download),
onPressed: () {
_downloadZip();
},
),
],
),
body: Container(
child: Column(
children: <Widget>[
buildList(),
],
),
),
);
}
}
_initDir() async {
if (null == _dir) {
_dir = (await getApplicationDocumentsDirectory()).path;
print("current dir--$_dir")
}
}
use like this

How to Display Download Progress in Alert Dialog box using Dio package

I am Currently trying to download a file from URL using Dio Package. I can successfully download the file but I want to display the progress in an Alert Dialog and once Download is Successful Then it Should Display "Download Successful". I tried but couldn't find any solution
Packages I used are : Dio, Path_Provider and permission_handler.
my Code :
class WatchView extends StatefulWidget {
#override
_WatchViewState createState() => _WatchViewState();
}
class _WatchViewState extends State<WatchView> {
final Dio dio = Dio();
bool loading = false;
double progress = 0;
Future<bool> saveVideo(String url, String fileName) async {
Directory directory;
try {
if (Platform.isAndroid) {
if (await _requestPermission(Permission.storage)) {
String newPath =
"storage/emulated/0/Android/data/com.appname.test./files/";
print(directory);
newPath = newPath + "folder";
directory = Directory(newPath);
} else {
return false;
}
} else {
if (await _requestPermission(Permission.photos)) {
directory = await getTemporaryDirectory();
} else {
return false;
}
}
File saveFile = File(directory.path + "/$fileName");
if (!await directory.exists()) {
await directory.create(recursive: true);
}
if (await directory.exists()) {
await dio.download(url, saveFile.path,
onReceiveProgress: (value1, value2) {
setState(() {
progress = value1 / value2;
});
});
return true;
}
return false;
} catch (e) {
print(e);
return false;
}
}
Future<bool> _requestPermission(Permission permission) async {
if (await permission.isGranted) {
return true;
} else {
var result = await permission.request();
if (result == PermissionStatus.granted) {
return true;
}
}
return false;
}
downloadFile(String file1) async {
setState(() {
loading = true;
progress = 0;
});
bool downloaded = await saveVideo(file1, "test.file_extention");
if (downloaded) {
print("File Downloaded");
} else {
print("Problem Downloading File");
}
setState(() {
loading = false;
});
}
#override
Widget build(BuildContext context) {
var provider = Provider.of<ProviderModel>(context);
return Scaffold(
appBar: AppBar(
elevation: 0.0,
leading: GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: Icon(Icons.arrow_back, color: Colors.white),
),
),
body: SingleChildScrollView(
physics: ClampingScrollPhysics(),
child: Container(
),
floatingActionButton: FloatingActionButton.extended(
label: Text(
'Download',
),
backgroundColor: Colors.indigo[700],
icon: Icon(Icons.download_rounded),
onPressed: () {
downloadFile(
"Download URL,
);
},
),
floatingActionButtonLocation:
FloatingActionButtonLocation.centerFloat,
);
},
);
}
}

Download ZIP, Extract it and Show the images file but not load from Document Directory?

Hello friend I am creating project when user install my app first they download zip file from internet and extract all file inside it then show in my app but problem is that when user download and extracted file the image inside zip shown in app when I close app and reopen it again image not load from Document directory everytime they need click on download button then show the image in the app any one tell me what's issue here is code?
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:archive/archive.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
class DownloadAssetsDemo extends StatefulWidget {
DownloadAssetsDemo() : super();
final String title = "Download & Extract ZIP Demo";
#override
DownloadAssetsDemoState createState() => DownloadAssetsDemoState();
}
class DownloadAssetsDemoState extends State<DownloadAssetsDemo> {
//
bool _downloading;
String _dir;
List<String> _images, _tempImages;
String _zipPath = 'https://coderzheaven.com/youtube_flutter/images.zip';
String _localZipFileName = 'images.zip';
#override
void initState() {
super.initState();
_images = List();
_tempImages = List();
_downloading = false;
_initDir();
}
_initDir() async {
if (null == _dir) {
_dir = (await getApplicationDocumentsDirectory()).path;
}
}
Future<File> _downloadFile(String url, String fileName) async {
var req = await http.Client().get(Uri.parse(url));
var file = File('$_dir/$fileName');
return file.writeAsBytes(req.bodyBytes);
}
Future<void> _downloadZip() async {
setState(() {
_downloading = true;
});
_images.clear();
_tempImages.clear();
var zippedFile = await _downloadFile(_zipPath, _localZipFileName);
await unarchiveAndSave(zippedFile);
setState(() {
_images.addAll(_tempImages);
_downloading = false;
});
}
unarchiveAndSave(var zippedFile) async {
var bytes = zippedFile.readAsBytesSync();
var archive = ZipDecoder().decodeBytes(bytes);
for (var file in archive) {
var fileName = '$_dir/${file.name}';
if (file.isFile) {
var outFile = File(fileName);
//print('File:: ' + outFile.path);
_tempImages.add(outFile.path);
outFile = await outFile.create(recursive: true);
await outFile.writeAsBytes(file.content);
}
}
}
buildList() {
return Expanded(
child: ListView.builder(
itemCount: _images.length,
itemBuilder: (BuildContext context, int index) {
return Image.file(
File(_images[index]),
fit: BoxFit.fitWidth,
);
},
),
);
}
progress() {
return Container(
width: 25,
height: 25,
padding: EdgeInsets.fromLTRB(0.0, 20.0, 10.0, 20.0),
child: CircularProgressIndicator(
strokeWidth: 3.0,
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
actions: <Widget>[
_downloading ? progress() : Container(),
IconButton(
icon: Icon(Icons.file_download),
onPressed: () {
_downloadZip();
},
),
],
),
body: Container(
child: Column(
children: <Widget>[
buildList(),
],
),
),
);
}
}
You can copy paste run full code below
You can save and restore List<String> with package SharedPreferences
code snippet
getHistoryImageList() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_images = prefs.getStringList("images");
});
}
...
Future<void> _downloadZip() async {
...
await unarchiveAndSave(zippedFile);
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setStringList("images", _tempImages);
setState(() {
_images = List<String>.from(_tempImages);
_downloading = false;
});
}
working demo
full code
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:archive/archive.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
class DownloadAssetsDemo extends StatefulWidget {
DownloadAssetsDemo() : super();
final String title = "Download & Extract ZIP Demo";
#override
DownloadAssetsDemoState createState() => DownloadAssetsDemoState();
}
class DownloadAssetsDemoState extends State<DownloadAssetsDemo> {
//
bool _downloading;
String _dir;
List<String> _images, _tempImages;
String _zipPath = 'https://coderzheaven.com/youtube_flutter/images.zip';
String _localZipFileName = 'images.zip';
getHistoryImageList() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_images = prefs.getStringList("images");
});
}
#override
void initState() {
super.initState();
_images = [];
getHistoryImageList();
_tempImages = List();
_downloading = false;
_initDir();
}
_initDir() async {
if (null == _dir) {
_dir = (await getApplicationDocumentsDirectory()).path;
print("init $_dir");
}
}
Future<File> _downloadFile(String url, String fileName) async {
var req = await http.Client().get(Uri.parse(url));
var file = File('$_dir/$fileName');
print("file.path ${file.path}");
return file.writeAsBytes(req.bodyBytes);
}
Future<void> _downloadZip() async {
setState(() {
_downloading = true;
});
_images?.clear();
_tempImages?.clear();
var zippedFile = await _downloadFile(_zipPath, _localZipFileName);
await unarchiveAndSave(zippedFile);
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setStringList("images", _tempImages);
setState(() {
_images = List<String>.from(_tempImages);
_downloading = false;
});
}
unarchiveAndSave(var zippedFile) async {
var bytes = zippedFile.readAsBytesSync();
var archive = ZipDecoder().decodeBytes(bytes);
for (var file in archive) {
var fileName = '$_dir/${file.name}';
print("fileName ${fileName}");
if (file.isFile && !fileName.contains("__MACOSX")) {
var outFile = File(fileName);
//print('File:: ' + outFile.path);
_tempImages.add(outFile.path);
outFile = await outFile.create(recursive: true);
await outFile.writeAsBytes(file.content);
}
}
}
buildList() {
return _images == null
? Container()
: Expanded(
child: ListView.builder(
itemCount: _images.length,
itemBuilder: (BuildContext context, int index) {
return Image.file(
File(_images[index]),
fit: BoxFit.fitWidth,
);
},
),
);
}
progress() {
return Container(
width: 25,
height: 25,
padding: EdgeInsets.fromLTRB(0.0, 20.0, 10.0, 20.0),
child: CircularProgressIndicator(
strokeWidth: 3.0,
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
actions: <Widget>[
_downloading ? progress() : Container(),
IconButton(
icon: Icon(Icons.file_download),
onPressed: () {
_downloadZip();
},
),
],
),
body: Container(
child: Column(
children: <Widget>[
buildList(),
],
),
),
);
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: DownloadAssetsDemo(),
);
}
}

How to send dynamic url from DataProvider to PDF Flutter

I'm new to Flutter. I have DataProvider which consists of Pdf data like it's Title, pdfURL and etc and I created a ListView on that ListView I have some items.
Whenever I click on any item it should open specified pdf url on PDF VIEWER. I want to pass that data dynamically to the getFileFromUrl; how should I pass that data.
This is my DataProvider class:
class DataProvider with ChangeNotifier{
List<PdfBook> _pdfItems = [
PdfBook(
id: 'p1',
title: 'PDF Bookmark Sample',
pdfUrl: 'https://www.adobe.com/support/products/enterprise/knowledgecenter/media/c4611_sample_explain.pdf',
avatar: 'T',
),
PdfBook(
id: 'p2',
title: 'PDF 995',
pdfUrl: 'http://www.pdf995.com/samples/pdf.pdf',
avatar: 'T2',
),
];
List<PdfBook> get pdfItems{
return [..._pdfItems];
}
PdfBook findById(String id){
return _pdfItems.firstWhere((item) => item.id == id);
}
}
This is my PdfViewState:
class PdfItem extends StatefulWidget {
#override
_PdfItemState createState() => _PdfItemState();
}
class _PdfItemState extends State<PdfItem> {
String assetPDFPath = "";
String urlPDFPath = "";
#override
void initState() {
super.initState();
getFileFromAsset("assets/mypdf.pdf").then((f) {
setState(() {
assetPDFPath = f.path;
print(assetPDFPath);
});
});
getFileFromUrl("http://www.pdf995.com/samples/pdf.pdf").then((f) {
setState(() {
urlPDFPath = f.path;
print(urlPDFPath);
});
});
}
Future<File> getFileFromAsset(String asset) async {
try {
var data = await rootBundle.load(asset);
var bytes = data.buffer.asUint8List();
var dir = await getApplicationDocumentsDirectory();
File file = File("${dir.path}/mypdf.pdf");
File assetFile = await file.writeAsBytes(bytes);
return assetFile;
} catch (e) {
throw Exception("Error opening asset file");
}
}
Future<File> getFileFromUrl(String url) async {
try {
var data = await http.get(url);
var bytes = data.bodyBytes;
var dir = await getApplicationDocumentsDirectory();
File file = File("${dir.path}/mypdfonline.pdf");
File urlFile = await file.writeAsBytes(bytes);
return urlFile;
} catch (e) {
throw Exception("Error opening url file");
}
}
#override
Widget build(BuildContext context) {
final pdf = Provider.of<PdfBook>(context, listen: false);
return ListTile(
title: Text(pdf.title),
onTap: () {
if (urlPDFPath != null) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
PdfViewPage(path: urlPDFPath)));
}
},
leading: CircleAvatar(
child: Text(pdf.avatar),
backgroundColor: Theme.of(context).accentColor,
),
trailing: Icon(Icons.arrow_right),
);
}
}
This is my ListView Class:
class PdfListView extends StatelessWidget {
#override
Widget build(BuildContext context) {
final pdfData = Provider.of<DataProvider>(context);
final pdf = pdfData.pdfItems;
return Scaffold(
appBar: AppBar(
title: Text("PDF Books"),
),
body: ListView.builder(
itemCount: pdf.length,
itemBuilder: (ctx, i) => ChangeNotifierProvider.value(
value: pdf[i],
child: PdfItem(),
),
),
);
}
}