Home > database >  A value of type 'XFIle' can't be assigned to a variable of type 'File' erro
A value of type 'XFIle' can't be assigned to a variable of type 'File' erro

Time:11-10

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;
  });

CodePudding user response:

you can conver XFile to File using following line:

selectedImage = File(image.path);

CodePudding user response:

First, you should create your variable as XFile

Because this is what you get from image picker.

  XFile photo;
  void _pickImage() async {
    final ImagePicker _picker = ImagePicker();

    photo = await _picker.pickImage(source: ImageSource.camera);
    if (photo == null) return;

  }

And then you can use your image as a file image.

 Image.file(File(photo.path))

CodePudding user response:

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:

late 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
  • Related