Imagepicker 'XFile' is not a subtype of type 'File' in type cast 和 Firebase Storage 图片上传错误

Imagepicker 'XFile' is not a subtype of type 'File' in type cast and Firebase Storage image upload error

我正在尝试 select 使用图像选择器从图库中获取图像并将其上传到 firebasestorage。 当应用程序运行时,它给出错误“无法打开文件,路径 = ''(OS 错误:错误地址,errno = 14)和未处理的异常:类型 'XFile' 不是类型 'File' 在类型转换中'.

GestureDetector(
                  onTap: () => pickPhotoFromGallery(),
                  child: CircleAvatar(
                    radius: 70,
                    // ignore: unnecessary_null_comparison
                    child: (_imageFile != null)
                        ? Image.file(_imageFile)
                        : Image.asset('assets/images/icon.png'),
                  ),
                ),

Future pickPhotoFromGallery() async {
    File imageFile =
        (await _imagePicker.pickImage(source: ImageSource.gallery)) as File;

    setState(() {
      _imageFile = imageFile;
    });
  }

当我点击保存按钮时,它显示“断言失败:第 127 行第 12 行: 'file.absolute.existsSync()':这不是真的。”我遇到了错误。

onPressed: uploading ? null : () => uploadImageAndSaveItemInfo(),
  uploadImageAndSaveItemInfo() async {
    setState(() {
      uploading = true;
    });

    String imageDownloadUrl = await uploadItemImage(_imageFile);

    saveItemInfo(imageDownloadUrl);
    saveItemInfoCategory(imageDownloadUrl);
  }


  Future<String> uploadItemImage(File mFileImage) async {
    final Reference storageReference =
        FirebaseStorage.instance.ref().child("thumbnail");

    UploadTask uploadTask = storageReference
        .child(_idController.text.trim() + ".jpg")
        .putFile(mFileImage);

    String downloadUrl = await uploadTask.snapshot.ref.getDownloadURL();
    return downloadUrl;
  }

Imagepicker 在旧版本中工作,在最新版本中出现错误。

这是因为图像选择器已升级为使用 Xfile 而不是 File。要将 Xfile 转换为 File,您可以使用:

File file = File( _imageFile.path );

您还需要添加 import 'dart:io'