Home > Software engineering >  _CastError (type 'XFile' is not a subtype of type 'File' in type cast)
_CastError (type 'XFile' is not a subtype of type 'File' in type cast)

Time:05-20

how are you?

I'm developing a store management app and, when registering a product, I need its photo. But, when taking the picture in the emulator camera, nothing happens, I just realized that I have this _CastError. About XFile is not a File.

Code snippet

 ElevatedButton(
            child: Text("Câmera"),
            onPressed: () async {
              File image = await ImagePicker()
                  .pickImage(source: ImageSource.camera) as File;
              imageSelected(image);
            },
          )

picture error

CodePudding user response:

The reason for this is that the image picker was upgraded to use Xfile instead of File. To convert Xfile to File you can use:

File file = File( _imageFile.path );

You will need to add import 'dart:io' as well.

CodePudding user response:

I'd put this as a response to G H Prakash's answer, but the formatting isn't there then, so you'd use it like this in your code. Basically, you get it as an XFile, then load it as a normal file and use it for further processing.

ElevatedButton(
  child: Text("Câmera"),
  onPressed: () async {
    XFile ximage = await ImagePicker().pickImage(source: ImageSource.camera);
    
    // load the image as File
    File image = File(ximage.path);
    imageSelected(image);
  },
)

The reason ImagePicker uses XFiles is for compatibility with Flutter Web, so you could also look into integrating XFiles in your further processing workflow.

  • Related