Flutter 'File' can't be assigned to 'XFile' - flutter

I have a function to save network image to local cache files, but I have a trouble when store the list file that I downloaded to List<XFile>. Here is my download function:
List<XFile>? imageFileList = [];
Future<File> downloadImage(url, filename) async {
var httpClient = HttpClient();
try {
var request = await httpClient.getUrl(Uri.parse(url));
var response = await request.close();
var bytes = await consolidateHttpClientResponseBytes(response);
final dir = await getTemporaryDirectory();
File file = File('${dir.path}/$filename');
await file.writeAsBytes(bytes);
print('downloaded file path = ${file.path}');
return file;
} catch (error) {
print('download error');
return File('');
}
}
is there any way so I can save the file to imageFileList as :
imageFileList!.add(file);

Convert the file to XFile:
XFile file = new XFile(file.path);

Change your list type:
from this:
List<XFile>? imageFileList = [];
to this:
List<File>? imageFileList = [];
final ImagePicker _picker = ImagePicker();
getImage() async {
var images = await _picker.pickMultiImage();
images!.forEach((image) {
setState(() {
_imageFileList!.add(File(image.path));
});
});
}

Related

Cannot get the download link after uploading files to firebase storage Flutter

so this is the my file picking and file upload code
class Storage with ChangeNotifier {
PlatformFile? pickedFile;
UploadTask? uploadTask;
Future uploadFile() async {
final path = 'files/${pickedFile!.name}.png';
final file = File(pickedFile!.path!);
final ref = FirebaseStorage.instance.ref().child(path);
ref.putFile(file);
try {
final snapshot = await uploadTask!.whenComplete(() {});
final urlDownload = await snapshot.ref.getDownloadURL();
print(urlDownload);
} catch (e) {
print("this is the error $e " );
}
}
void pickFile() async {
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
File file = File(result.files.single.path!);
pickedFile = result.files.first;
} else {
print("no image picked");
}}}
the code works for upload the image but after that i didnt get any download link, the error is "Null check operator used on a null value" i dont know how to fix it, im still new in this topic, help please
i got the answer, need to change the uploadFile method to this
Future uploadFile() async {
final path = 'files/${pickedFile!.name}.png';
final file = File(pickedFile!.path!);
FirebaseStorage storage = FirebaseStorage.instance;
Reference ref = storage.ref().child(path);
UploadTask uploadTask = ref.putFile(file);
uploadTask.then((res) {
res.ref.getDownloadURL();
});
try {
final snapshot = await uploadTask.whenComplete(() {});
final urlDownload = await snapshot.ref.getDownloadURL();
print(urlDownload);
} catch (e) {
print("this is the error $e " );
}
}

upload image by flutter in firebase Storage

I try to upload an image on firebase storage and get the error.
Future selectImage(ImageSource source) async {
try {
XFile? xImage = await ImagePicker().pickImage(source: source);//getting picture from phone
if(xImage == null ) return 'there is no image';
final File file = File(xImage.path);
//final Image image = Image.file(File(xImage.path));
print(xImage.path);
Directory appDocDir = await getApplicationDocumentsDirectory();
String filePath = '${appDocDir.absolute}/file-to-upload.png';
print(filePath);
final storageRef = FirebaseStorage.instance.ref().child("UsersProfilePhoto/");
await storageRef.putFile(file);
} on FirebaseException catch (e) {
print(e.message);
}
}
Try like this.
Future selectImage(ImageSource source) async {
try {
ImagePicker imagePicker = ImagePicker();
XFile pickedFile = await imagePicker.pickImage(source: source, imageQuality: 80);
File imageFile = File(pickedFile.path);
if(imageFile == null ) return 'there is no image';
print(imageFile.path);
String fileName = DateTime.now().millisecondsSinceEpoch.toString();
final storageRef = FirebaseStorage.instance.ref().child("UsersProfilePhoto/");
await storageRef.putFile(imageFile);
} on FirebaseException catch (e) {
print(e.message);
}
}
Try this
import 'package:path/path.dart' as Path1;//for storing image path in firestore
DatabaseReference reference = FirebaseDatabase.instance.reference();
FirebaseStorage storage = FirebaseStorage.instance;
File? fileImage;
//call this function for picking image
pickedImage() async{
PickedFile? file = await ImagePicker().getImage(
source: ImageSource.camera,
maxHeight: 1000,
maxWidth: 1000
);
File image = file!.path;
setState((){
fileImage = image;
});
}
//call this function for storing image in firestore
_storeImage() async{
Reference storagerefrence = storage.ref().child('card_images/${Path1.basename(fileImage!.path)}');
TaskSnapshot uploadTask = await storagerefrence.putFile(fileImage!);
String url = await storagerefrence.getDownloadURL();//download url from firestore and add to firebase database
reference.child("image").push().set({
'image' : url
});
}

Flutter App for encryption an audio for secure

I have a project with encrypt an audio for secure my data audio and when the user purchase they can play the audio, but until now didn't find how to do that. I found another way by converting the audio data into a string and then encrypting it, I found a code but it's incomplete so I'm still confused about using it.
import 'dart:io';
import 'dart:typed_data';
import 'package:file_picker/file_picker.dart';
import 'package:path_provider/path_provider.dart';
class MediaFile {
Future<String> get docPath async {
Directory appDocDir = await getApplicationDocumentsDirectory();
return appDocDir.path;
}
Future<Uint8List> get audioFileData async {
final String path = await docPath;
final String theFilePath = '$path/test.mp3';
final File theFile = new File(theFilePath);
if (await theFile.exists()) {
return await theFile.readAsBytes();
} else {
File file = await FilePicker.getFile();
return await file.readAsBytes();
}
}
Future<String> dataToString() async {
Uint8List data = await audioFileData;
return new String.fromCharCodes(data);
}
Future<File> saveMediaAsString(String fileName, String fileContent) async {
String path = await docPath;
Directory dataDir = new Directory('$path/data');
if (await dataDir.exists()) {
File file = new File('$path/data/$fileName');
return file.writeAsString(fileContent);
}
await dataDir.create();
File file = new File('$path/data/$fileName');
return file.writeAsString(fileContent);
}
Future<String> readFromStringMediaFile(String fileName) async {
String path = await docPath;
File file = new File('$path/data/$fileName');
return file.readAsString();
}
Uint8List stringToData(dataStr) {
List<int> list = dataStr.codeUnits;
return new Uint8List.fromList(list);
}
Future<File> createAudioFile(String fileName, Uint8List bytes) async {
String path = await docPath;
File file = new File('$path/$fileName');
return await file.writeAsBytes(bytes);
}
//here you can see how to use them
Future<File> testFile() async {
String dataStr = await dataToString();
File savedFile = await saveMediaAsString('codedFile', dataStr);
String contentSavedFile = await readFromStringMediaFile('codedFile');
Uint8List bytes = stringToData(contentSavedFile);
return await createAudioFile('test.mp3', bytes);
}
}

How to save and create files in internal device storage flutter

How can I save and create files in internal device storage in flutter? When I create file with getExternalStorageDirectory(), the file hasn't appeared in internal storage.
String fileExtension = name!.split('.').last;
String fileName =
name!.replaceAll('.${fileExtension}', '');
String? localPath = await _findLocalPath();
String completePath = '${localPath}/${fileName}.${fileExtension}';
logger.e(completePath);
io.File file = io.File(completePath);
await file.writeAsBytes(dataStore);
file.create();
Future<String?> _findLocalPath() async {
String? externalStorageDirPath;
if (io.Platform.isAndroid) {
final io.Directory? directory = await getExternalStorageDirectory();
externalStorageDirPath = directory!.path;
} else if (io.Platform.isIOS) {
externalStorageDirPath =
(await getApplicationDocumentsDirectory()).absolute.path;
}
final io.Directory savedDir = io.Directory(externalStorageDirPath!);
bool hasExisted = await savedDir.exists();
logger.e(hasExisted);
if (!hasExisted) {
logger.e('Create Folder');
savedDir.create();
}
return externalStorageDirPath;
}
Can anyone help me?
Try replacing the top block of code with this:
String fileExtension = name!.split('.').last;
String fileName =
name!.replaceAll('.${fileExtension}', '');
String? localPath = await _findLocalPath();
String completePath = '${localPath}/${fileName}.${fileExtension}';
logger.e(completePath);
io.File file = io.File(completePath);
//await file.writeAsBytes(dataStore);
//file.create();
var output = file.openWrite(mode: FileMode.writeOnlyAppend);
await for (final data in dataStore) {
output.add(data);
}
await output.close();

Flutter esys_flutter_share and image picker saver not working

I am trying to download an image and the save image. It’s downloading the image but it’s not opening the share. What am I missing here. I am using this package esys_flutter_share 1.0.2
and image_picker_saver 0.3.0
void onImageDownLoad(Product product, isLoading) async {
final String text = "${product.name}\n\n${product.description}";
var request = await HttpClient().getUrl(Uri.parse(product.image));
var response = await request.close();
isLoading = true;
Uint8List bytes = await consolidateHttpClientResponseBytes(response);
var filepath = await ImagePickerSaver.saveFile(fileData: bytes);
final ByteData newBytes = await rootBundle.load(filepath);
isLoading = false;
await Share.file('ESYS AMLOG', 'amlog.jpg', bytes, 'image/jpg',
text: text);
}
So finally figured it out imagePicker saver is a future and need to be completed before the share is called.So I added whenComplete.
void onImageDownLoad(Product product, isLoading) async {
isLoading = true;
final String text = "${product.name}\n\n${product.description}";
var req = await HttpClient().getUrl(Uri.parse(product.image));
var response = await req.close();
isLoading = false;
Uint8List bytes = await consolidateHttpClientResponseBytes(response);
await ImagePickerSaver.saveFile(fileData: bytes).whenComplete(() {
EsysShare.Share.file('ESYS AMLOG', 'amlog.jpg', bytes, 'image/jpg',
text: text);
});
}