How to open pdf file in the app using Flutter - flutter

I am using flutter_pdfview which is version ^1.0.0+10 to open a PDF file in flutter apps. When my app is in debug mode, there is no error. After I build the app the PDF file cannot open in apps. My app will crash and close suddenly. I have open the permission in AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
How can solve this error?

First you need to create a proguard-rules.pro file at /android/app/ inside there write like this:
#Flutter Wrapper
-keep class com.shockwave.**
Then at /android/app/build.gradle add this:
buildTypes {
release {
signingConfig signingConfigs.release
**minifyEnabled true
useProguard true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'**
}
}

I have this problem only on android but when the app is on production. To fix this I add the permission handler plugin and change the path. Also and very important was add the extension ".pdf" to file after download but before read.
final filename = url.substring(url.lastIndexOf("/") + 1);
var request = await HttpClient().getUrl(Uri.parse(url));
var response = await request.close();
var bytes = await consolidateHttpClientResponseBytes(response);
String dir = (await getExternalStorageDirectory()).path;
File file = new File('$dir/$filename.pdf');
await file.writeAsBytes(bytes);
pathPDF = file.path;
return file;

If you are running debug on an emulator and then release on a real device, this might be your problem:
PdfViewPage(path: '/storage/emulated/0/Download/$pdfName')));
Even if it isn't causing the crash it is a bad idea to hardcode download path like you've done. Different devices can have downloads in different locations. You can use downloads_path_provider to find where downloads is located.
Also, beside declaring the permissions needed in the Manifest you should also ask user for permission and handle the situation if the user doesn't give permission. For that task I suggest using permission_handler.

Related

requires android.permission.WRITE_EXTERNAL_STORAGE, or grantUriPermission()

when using Image-Picker package and run ,this exception is showing . image is not shows in the container after taking the image..
Beside needing to add WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE to your android/app/src/main/AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xxx.yyy">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
...
</manifest>
You also need Runtime Request Permission, by using permission_handler package:
import 'package:simple_permissions/simple_permissions.dart';
PermissionStatus permissionResult = await SimplePermissions.requestPermission(Permission. WriteExternalStorage);
if (permissionResult == PermissionStatus.authorized){
// code of read or write file in external storage (SD card)
}
Note:
when running SimplePermissions.requestPermission for the First Time, app will pop up a window, you MUST click ALLOW:
to give permission.
If you already clicked DENY, then uninstall debug app and re-debug it to install and fix this -> trigger the popup window and give you chance to click ALLOW.

Flutter how get local download folder with path_provider

At the moment i build a chat similar in wahtsapp.
I would like upload some local files (pdf, txt, image...).
Like this:
I try to get the local files via path_provider.
But i dont get access to download folder.
My problem:
I don't know how i can access the dowload folder with path_provider.
See my code:
//load local files from download folder
_loadLocalFile() async {
//absoulute path to download file
var file = io.Directory('/storage/emulated/0/Download/')
.listSync(); //use your folder name insted of resume.
//console output -> []
//other try to get download folder
List<io.Directory>? documents = await getExternalStorageDirectories();
//console output -> [Directory: '/storage/emulated/0/Android/data/de.securebuy.securebuy/files', Directory: '/storage/1BEC-0908/Android/data/de.securebuy.securebuy/files']
print(documents.toString());
}
I also add to AndroidManifest following rules:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE”/>
Anyone have a idea how i can build a function similar in image?
Is that possible?
Many thx
till now , pathprovider isn't going to let you in downloads file , so if you are on android you can just write the downloads directory , else using android_path_provider it is a null-safety package and you can accsess it via :var downloadsPath = await AndroidPathProvider.downloadsPath; , on ios you can get only the app directory cuase ios makes it's own file for every app thus we use 'pathprovider' with Directory appDocDir = await getApplicationDocumentsDirectory();
Update :
i see what you are trying to achieve and this is not what pathprovider pcakage is used for , you have to use file_picker , read thier docs , i thinks that this is what you need

I can view PDF file on emulator only nut not on a real device in Flutter application

I used import 'package:advance_pdf_viewer/advance_pdf_viewer.dart'; to view PDF files from the an asset directory, it works well on the emulator but when I installed the APK file on my mobile, the indicator spin and the PDF file is not displayed, also no crash for the application
and notice that there a message in the console but at the same time the file is displayed on the emulator
A resource failed to call close.
I/ple.flutter_ap(12020): NativeAlloc concurrent copying GC freed 1875(113KB) AllocSpace objects, 0(0B) LOS objects, 53% free, 1355KB/2MB, paused 6.847ms total 92.795ms
I searched on the net and I tried the following solution but it didn't work
Add this line of code to it:
-keep class com.shockwave.** { *; }
Now in your app level build.gradle file, add this to your buildType:
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
So that your buildType folder looks something like this:
buildTypes {
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.debug
}
}
enter code here
This is the code of getting the PDF file and it works well but only on the emulator
loadDocument() async {
document = await PDFDocument.fromAsset('assets/sample4.pdf');
setState(() => _isLoading = false);
}
The problem is related to memory and anti-virus, so I deleted or unneeded code and asked the anti-virus to resolve any issue with the APK file and the application after the installation

Flutter desktop windows get application path

I am creating a Flutter Desktop application for windows and I am trying to retrieve the application directory where the exe is located. I tried to use path_provider but can only get the Documents directory. Any help I would appreciate lots.
Use Platform.resolvedExecutable
(of dart:io).
I have tested it in Flutter/Windows and it works.
Strangely, Platform.executable returns null instead. I tell strangely because its type is String not nullable. This unexpected null value can cause crash or errors that are difficult to detect (but in the end Flutter desktop is not in the stable channel).
String dir = Directory.current.path;
print(dir);
Directory.current.path (in the dart:io package) returns the current working directory of the project folder (when developing) or the executable directory when running from a release build.
Try is package: path_provider
set this code in pubspec.yaml
dependencies:
path_provider: ^1.6.27 # get last Version From https://pub.dev/packages/path_provider/install
Code
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path; //C:\Users\USER_NAME\AppData\Local\Temp
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path; //C:\Users\USER_NAME\Documents
//Warning: on debug mode this code get location project but in release mode will get your location app correctly
String dir = Directory.current.path; // PATH_APP

Unable to load asset (file the app created)

Why does this cause a crash?
final directory = await getApplicationDocumentsDirectory();
final testFile = File("${directory.path}/test.txt");
await testFile.writeAsString("Hello there!", flush: true);
final ByteData bytes = await rootBundle.load(testFile.path);
The rootBundle.load() call causes:
Unhandled Exception: Unable to load asset: /data/user/0/com.flutter.tests/app_flutter/test.txt
BUT if I do a hot reload then it works fine until I restart the app.
I have a dependency path_provider: any in pubspec.yaml which is needed for the getApplicationDocumentsDirectory().
rootBundle only contains assets that were specified by pubspec.yaml and were built with your application. It's not supposed to access files created within file system. Use File or Image classes to open created files.
final bytes = testFile.readAsBytesSync();
The rootBundle contains the resources that were packaged with the
application when it was built. To add resources to the rootBundle for
your application, add them to the assets subsection of the flutter
section of your application's pubspec.yaml manifest.