Imagepicker“XFile”不是类型转换中“File”类型的子类型并且 Firebase 存储图像上传错误

Sem*_*maz 4 firebase flutter firebase-storage

我正在尝试使用 imagepicker 从图库中选择图像并将其上传到 firebasestorage。当应用程序运行时,它会给出错误“无法打开文件,path = ''(操作系统错误:错误地址,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;
    });
  }
Run Code Online (Sandbox Code Playgroud)

当我单击“保存”按钮时,它显示“断言失败:第 127 行第 12 行:‘file.absolute.existsSync()’:不正确。” 我遇到了错误。

onPressed: uploading ? null : () => uploadImageAndSaveItemInfo(),
Run Code Online (Sandbox Code Playgroud)
  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;
  }

Run Code Online (Sandbox Code Playgroud)

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

小智 16

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

File file = File( _imageFile.path );
Run Code Online (Sandbox Code Playgroud)

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