Flutter - I am unable to load file using File Picker package - flutter

I am trying to select a file using the File Picker package but it gives an error of Unable to load asset: /data/user/0/com.example.demo_app/cache/file_picker/sample1.txt
After selecting the file, I write code to make some implementattion of adding some quotation marks to it but the file won't even load
Below is the code for that:
String? fileResult;
Text? zeroTurniton;
PlatformFile? firstFile;
pw.Document? pdf;
Future<void> pickAndEditFile() async {
FilePickerResult? files = await FilePicker.platform.pickFiles(
allowedExtensions: ['doc', 'txt', 'docx'],
type: FileType.custom,
allowMultiple: false,
);
if (files == null) {
return;
} else {
print('------------${firstFile?.name}----------');
try {
firstFile = files.files.first;
String result;
result = await rootBundle.loadString(firstFile!.path!);
setState(() {
fileResult = result;
});
Text quote = const Text(
'"',
style: TextStyle(color: Colors.white),
);
zeroTurniton = Text(quote.toString() + result + quote.toString());
} catch (e) {
print(e.toString()); //**Prints the error here**
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(e.toString()),
backgroundColor: Theme.of(context).errorColor,
),
);
}
}
}

Okay so I just changed the File Picker package and it worked fine

Related

I'm having access issues when using the class I created

Like this I have a code:
final Storage storage = Storage();
// ....
onPressed: () async {
final results = await FilePicker.platform.pickFiles(
type: FileType.image,
allowMultiple: false,
allowedExtensions: ['jpg', 'png', "jpeg"],
);
if (results == null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("Resim seƧmediniz."),
backgroundColor: Color.fromARGB(255, 36, 36, 36),
),
);
return null;
}
final path = results.files.single.path!;
final fileName = results.files.single.name;
Storage.uploadFile(path, fileName);
},
Also I have storage_services.dart:
import 'dart:io';
import 'package:firebase_storage/firebase_storage.dart';
class Storage {
final FirebaseStorage _storage = FirebaseStorage.instance;
Future<void> uploadFile(String filePath, String fileName) async {
File file = File(filePath);
try {
await _storage.ref("$fileName").putFile(file);
} on Exception catch (e) {
print(e);
}
}
}
My codes were like this. I am getting an error. Error:
Instance member 'uploadFile' can't be accessed using static access.dartstatic_access_to_instance_member
I'm trying to code by looking at this video: https://www.youtube.com/watch?v=sM-WMcX66FI
How can I solve the problem? Thanks in advance for your help.

file downloader app with package sn progress dialog

How to change the progress_dialog package to the sn_progress_dialog package? I'm trying to make a file downloader app with a progress dialog, but the progress_dialog package is not null safety.
Future _downloadAndSaveFileToStorage(String urlPath) async {
final name = urlPdf.split('/').last;
ProgressDialog pr;
pr = ProgressDialog(context, type: ProgressDialogType.Normal);
pr.style(message: "Download file ...");
try{
await pr.show();
final Directory _documentDir = Directory('/storage/emulated/0/MyDocuments/$name');
await dio!.download(urlPath, _documentDir.path, onReceiveProgress: (rec, total){
setState(() {
_isLoading = true;
progress = ((rec / total)*100).toStringAsFixed(0) + " %";
print(progress);
pr.update(message: "Please wait : $progress");
});
});
pr.hide();
_fileFullPath = _documentDir.path;
} catch (e) {
print(e);
}
setState(() {
_isLoading = false;
});
}
And this is my screenshot app with progress_dialog package.
Just do like this :
Future _downloadAndSaveFileToStorage(String urlPath) async {
final name = urlPdf.split('/').last;
ProgressDialog pd = ProgressDialog(context: context);
try{
pd.show(max: 100, msg: 'Download file ...');
final Directory _documentDir = Directory('/storage/emulated/0/MyDocuments/$name');
await dio!.download(urlPath, _documentDir.path, onReceiveProgress: (rec, total){
setState(() {
_isLoading = true;
progress = ((rec / total)*100).toStringAsFixed(0) + " %";
print(progress);
pd.update(progress);
});
});
pd.close();
_fileFullPath = _documentDir.path;
} catch (e) {
pd.close();
print(e);
}
setState(() {
_isLoading = false;
});
}
and you can change color or message in show method like this :
pd.show(
max: 100,
msg: 'Preparing Download...',
progressType: ProgressType.valuable,
backgroundColor: Color(0xff212121),
progressValueColor: Color(0xff3550B4),
progressBgColor: Colors.white70,
msgColor: Colors.white,
valueColor: Colors.white);
just need a little tweaking :
Future _downloadAndSaveFileToStorage(String urlPath) async {
final name = urlPdf.split('/').last;
ProgressDialog pd = ProgressDialog(context: context);
try{
pd.show(
max: 100,
msg: 'Preparing Download...',
progressType: ProgressType.valuable,
backgroundColor: Color(0xff212121),
progressValueColor: Color(0xff3550B4),
progressBgColor: Colors.white70,
msgColor: Colors.white,
valueColor: Colors.white
);
final Directory _documentDir = Directory('/storage/emulated/0/MYDocuments/$name');
await dio!.download(urlPath, _documentDir.path, onReceiveProgress: (rec, total){
setState(() {
_isLoading = true;
int progress = (((rec / total) * 100).toInt());
print(progress);
pd.update(value: progress, msg: 'File Downloading');
});
});
pd.close();
_fileFullPath = _documentDir.path;
} catch (e) {
pd.close();
print(e);
}
setState(() {
_isLoading = false;
});
}

ImagePicker.platform shows warning - Flutter

I am using the following code to pick an image from user's gallery.
Future getImageFromGallery(BuildContext context) async {
await ImagePicker.platform()
.pickImage(source: ImageSource.gallery)
.then((image) {
if (image != null) {
_cropImage(image, context);
}
});
}
I am getting the following warning.
The member 'platform' can only be used within 'package:image_picker/image_picker.dart' or a test.
I'm not sure what the warning means. I tried looking it up but couldn't figure out the solution to resolve this warning.
Try below code hope its help to you
Declare File type form dart.io package
File? imagePicked;
Create Function for pick up the image
void gallaryImage() async {
final picker = ImagePicker();
final pickedImage = await picker.pickImage(
source: ImageSource.gallery,
);
final pickedImageFile = File(pickedImage!.path);
setState(() {
imagePicked = pickedImageFile;
});
}
Create your Widget
TextButton(
onPressed: gallaryImage,
child: Text(
'Gallery',
style: TextStyle(
color: Colors.black,
),
),
),
You can just change the code
ImagePicker.platform().pickImage(...)
to
ImagePicker().pickImage(...)
so
Future getImageFromGallery(BuildContext context) async {
await ImagePicker()
.pickImage(source: ImageSource.gallery)
.then((image) {
if (image != null) {
_cropImage(image, context);
}
});
}

Flutter file_picker package giving null value for all file details

I've copied the same code from file_picker package docs, but it keeps giving me a null value for all file details, here is the code I've copied
FilePickerResult result = await FilePicker.platform.pickFiles();
if(result != null) {
PlatformFile file = result.files.first;
print(file.name);
print(file.bytes);
print(file.size);
print(file.extension);
print(file.path);
}
The file name, bytes, size, extension and path are all giving a null value. Anyone know what is the reason for that ?
I've tried to upload a pdf, png, jpg, doc and get the same null value for all of them.
I'm using the latest version of this:
https://pub.dev/packages/file_picker
void _openFileExplorer() async {
File _pickedFile;
FilePickerResult _filePickerResult;
setState(() {
_isLoading = true;
});
try {
_filePickerResult = await FilePicker.platform.pickFiles(
type: FileType.any,
allowedExtensions: (_extension?.isNotEmpty ?? false)
? _extension?.replaceAll(' ', '')?.split(',')
: null);
} on PlatformException catch (e) {
print("Unsupported operation" + e.toString());
}
if (_filePickerResult != null) {
setState(() {
_pickedFile = File(_filePickerResult.files.single.path);
});
}
if (!mounted) return;
{
Flushbar(
showProgressIndicator: true,
progressIndicatorBackgroundColor: Colors.blueGrey,
title: 'Status:',
message: 'File loaded: $_pickedFile',
duration: Duration(seconds: 3),
backgroundColor: Colors.green,
)
..show(context);
}
setState(() {
_isLoading = false;
});
}

Issue downloading images using image_downloader package

So, I have been successful in downloading an image from a firebase URL and storing it in the device, The issue that I am facing is that it also downloads a file with the same name as the downloaded image, but without file type.
Example, downloading Image.jpg will also download a file named Image, and it is visible within the device.
saveImage(Message message) async {
String url = message.photoURL;
try {
var imageId = await ImageDownloader.downloadImage(
url,
destination: AndroidDestinationType.custom(directory: 'exampleDir'),
);
if (imageId == null) {
return;
}
setState(() {
SnackBar snackBar = SnackBar(
content: Text('Image Saved!'),
);
_scaffoldKey.currentState.showSnackBar(snackBar);
Timer(Duration(seconds: 2), () {});
});
if (imageId == null) {
return;
}
} on PlatformException catch (error) {
print(error);
}
}
Any suggestions?
Thanks