skip to Main Content

The error is this : A value of type ‘XFile?’ can’t be assigned to a variable of type ‘File’. I tried changing the type of the variable "picture", from File to XFile, and it gives me this error instead: A value of type ‘XFile?’ can’t be assigned to a variable of type ‘XFile’.

This is my code so far:

void _openCamera() async {
    if(imagenes.length == 8) {
      alerta(contextMain, 'Limites de imagenes');
    }
    else {
      
      File picture = await ImagePicker.pickImage(source: ImageSource.camera, imageQuality: 75);
      int pos = imagenes.length;

      imagenes.add({pos:picture});
      setState(() {});
      await jsonBloc.cargarImagen( picture ).then((value) {
        int id = value; 
        imagenes[pos] = { id: picture };
      });
    }
  }

3

Answers


  1. ImagePicker.pickImage is a Future that returns an XFile?, which means it can either return an actual XFile, or null.

    So your variable picture needs to be an XFile? as well. So keep in mind in the rest of your code that picture can be null.

    Login or Signup to reply.
  2. You can get file like

    XFile? picture = await ImagePicker()
        .pickImage(source: ImageSource.camera, imageQuality: 75);
    if (picture != null) {
      final File imageFile = File(picture.path);
    }
    
    Login or Signup to reply.
  3. This happens because the package (image_picker ) you are using is relying on XFile and not File, as previously done.

    So, first, you have to create a variable of type File so you can work with it 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search