A value of type 'XFIle' can't be assigned to a variable of type 'File' error

Issue

I am using image_picker: ^0.8.4+4 where I am getting this error. what I can do to make this code right?

late File selectedImage;
bool _isLoading = false;
CrudMethods crudMethods = CrudMethods();

Future getImage() async {
var image = await ImagePicker().pickImage(source: ImageSource.gallery);

setState(() {
  selectedImage = image; //A value of type 'XFIle' can't be assigned to a variable of type 'File' error.
});
}

uploadBlog() async {
// ignore: unnecessary_null_comparison
if (selectedImage != null) {
  setState(() {
    _isLoading = true;
  });

Solution

This happens because the package (image_picker ) you are using is relying on XFile and not File, as previously did.

So, first you have to create a variable of type File so you can work with later as you did, and after fetching the selectedImage you pass the path to instantiate the File. Like this:

File? selectedImage;

bool _isLoading = false;
CrudMethods crudMethods = CrudMethods();

Future getImage() async {
var image = await ImagePicker().pickImage(source: ImageSource.gallery);

setState(() {
  selectedImage = File(image!.path); // won't have any error now
});
}

//implement the upload code

Answered By – Igor L Sambo

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *