I'm using image_picker
& ImageCropper
packages. I want to save a user-given picture in firestore database. So, I use functions like this.
First, set
File? _image;
Functions for cropping & picking
Future _pickImage(ImageSource source) async { Navigator.of(context).pop(); try { final image = await ImagePicker().pickImage(source: source); if (image == null) return; File? img = File(image.path); img = await _cropImage(imageFile: img); setState(() { _image = img; }); } on PlatformException catch (e) { print(e); Navigator.of(context).pop(); } } Future<File?> _cropImage({required File imageFile}) async { CroppedFile? croppedImage = await ImageCropper().cropImage(sourcePath: imageFile.path); if (CroppedFile == null) return null; return File(croppedImage!.path); }
and use this to save data in firestore
Future<String> uploadImageToStorage(
File file,
) async {
file
Reference ref =
_storage.ref().child("profilePics").child(_auth.currentUser!.uid);
UploadTask uploadTask = ref.putData(file);
TaskSnapshot snap = await uploadTask;
String downloadUrl = await snap.ref.getDownloadURL();
return downloadUrl;
}
Above function not work for File type data, It support for Uint8List. So, What can I do for this?
Next problem is, I'm getting File type data with ImagePicker for profile picture. Is it not problem?
CodePudding user response:
Try changing your _cropImage
-Method to return XFile?
like this:
Future<XFile?> _cropImage({required File imageFile}) async {
CroppedFile? croppedImage =
await ImageCropper().cropImage(sourcePath: imageFile.path);
if (CroppedFile == null) return null;
return XFile(croppedImage!.path);
}
You also have to change the paramter of uploadImageToStorage
to XFile file
. Then you can use file!.readAsBytes();
to get a Uint8List
.
Future<String> uploadImageToStorage(
XFile file,
) async {
Reference ref =
_storage.ref().child("profilePics").child(_auth.currentUser!.uid);
final fileBytes = await file.readAsBytes();
UploadTask uploadTask = ref.putData(fileBytes);
TaskSnapshot snap = await uploadTask;
String downloadUrl = await snap.ref.getDownloadURL();
return downloadUrl;
}