flutter 如何修复“XFile?”类型的值无法分配给“File”类型的变量的错误

jv4diomz  于 2023-03-31  发布在  Flutter
关注(0)|答案(3)|浏览(257)

错误是:类型为'XFile?'的值不能赋给类型为'File'的变量。我尝试将变量“picture”的类型从File更改为XFile,结果出现以下错误:不能将类型为“XFile?”的值赋给类型为“XFile”的变量
这是我的代码:

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

wmomyfyw1#

您可以获得如下文件

XFile? picture = await ImagePicker()
    .pickImage(source: ImageSource.camera, imageQuality: 75);
if (picture != null) {
  final File imageFile = File(picture.path);
}
e4eetjau

e4eetjau2#

ImagePicker.pickImage是一个返回XFile?的Future,这意味着它可以返回实际的XFilenull
所以你的变量picture也需要是一个XFile?。所以在剩下的代码中记住,picture可以是null

jhiyze9q

jhiyze9q3#

发生这种情况是因为您正在使用的包(image_picker)依赖于XFile而不是File,就像以前一样。
所以,首先,你必须创建一个File类型的变量,这样你就可以在以后像你做的那样使用它,在获取selectedImage之后,你传递路径来示例化File。像这样:

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

相关问题