无法将“XFIle”类型的值分配给“文件”类型的变量错误

Moh*_*ini 5 dart flutter flutter-dependencies flutter-layout imagepicker

我正在使用 image_picker: ^0.8.4+4 ,但出现此错误。我能做些什么来使这段代码正确?

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;
  });
Run Code Online (Sandbox Code Playgroud)

小智 11

您可以使用以下行将 XFile 转换为文件:

selectedImage = File(image.path);
Run Code Online (Sandbox Code Playgroud)


小智 5

首先,您应该将变量创建为XFile

因为这是你从图像选择器中得到的。

  XFile photo;
Run Code Online (Sandbox Code Playgroud)
  void _pickImage() async {
    final ImagePicker _picker = ImagePicker();

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

  }
Run Code Online (Sandbox Code Playgroud)

然后您可以将您的图像用作文件图像。

 Image.file(File(photo.path))
Run Code Online (Sandbox Code Playgroud)


Igo*_*mbo 4

发生这种情况是因为您使用的包 ( image_picker ) 依赖于 XFile 而不是 File,就像以前那样。

因此,首先您必须创建一个类型变量File,以便稍后可以像以前一样使用,并且在获取之后selectedImage传递路径来实例化文件。像这样:

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
Run Code Online (Sandbox Code Playgroud)