3

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;
  });
Mohit Saini
  • 33
  • 1
  • 1
  • 4

4 Answers4

9

you can conver XFile to File using following line:

selectedImage = File(image.path);
Jitendra Mistry
  • 342
  • 1
  • 11
5

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))
armancj2
  • 108
  • 1
  • 4
4

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
Igor L Sambo
  • 121
  • 7
  • The error is solved but it is still showing me a error in app the selected image has not been initialized . – Mohit Saini Nov 10 '21 at 12:34
  • Just edited the code, it won't throw the error now. I removed the late notation and made it nullable instead, since it's more feasible to use when the value it's first headed rather than created. Some references: [the late keyword](https://codewithandrea.com/videos/dart-null-safety-ultimate-guide-non-nullable-types/#the-late-keyword) – Igor L Sambo Nov 11 '21 at 21:50
0

XFile and File can be converted to each other like the following in Flutter:

import 'dart:io';
import 'package:camera/camera.dart';


XFile takenPhotoXFile = await _controller!.takePicture();

// XFile to File
File photoAsFile = File(takenPhotoXFile.path);

// File to XFile
 XFile imageFileAsXFile = XFile(photoAsFile.path);
Elmar
  • 2,235
  • 24
  • 22