首页 > 解决方案 > “无法转换:'_Uri'的实例”在flutter web上的cloud firestore最新版本上上传图像时出错

问题描述

cloud_firestore: ^0.14.0+2在云 Firestore 上上传图像时使用最新版本时出现以下错误。

Uncaught (in promise) Error: [cloud_firestore/unknown] Invalid argument (dartObject): Could not convert: Instance of '_Uri'

图像已成功上传到存储部分,但图像链接未在 cloud firestore db 中更新。

下面是我选择图像并点击他上传 btn 以上传图像的课程

class AddNewItemView extends StatefulWidget {
  @override
  _AddNewItemViewState createState() => _AddNewItemViewState();
}

class _AddNewItemViewState extends State<AddNewItemView> {
  MediaInfo _itemPic; 
 @override
  Widget build(BuildContext context) {
    return Scaffold(
    .....
    child: RawMaterialButton(
          onPressed: () async {
              MediaInfo pickedImg =  await ImagePickerWeb.getImageInfo; <---- image_picker_web package
               setState(() {
                 _itemPic = pickedImg;
                });
    .........
    FlatButton(
         onPressed: () async {
            bool addDataSuccess = await model.addNewItem( _itemPic);
            if (addDataSuccess) {
                 print("Inside addDataSuccess");
            } else {
                 print("Outside addDataSuccess");
                   }
                 },
              ),
    .....
    );
}

该类负责从函数中提取图片uriuploadImageFile并上传到cloud firestore. 与图片一起传递的任何其他信息都会上传到云火库中,只有“图片”没有上传

class ItemViewModel extends BaseViewModel {
           Future<bool> addNewItem(   MediaInfo pic ) async {
         
                 Uri _uploadedImgURL = await ConstantFtns()
                     .uploadImageFile(pic, "ImgPathString", "fileName");


     await  FirebaseFirestore.instance.collection('item').doc("tempID").set(
        {
              'pic': _uploadedImgURL,
          'otherInfo': 'otherTempInfo' 
    },
        );
}

在下面的课程中,我imageUri没有任何错误地有效,并且图像被上传到存储部分,唯一的问题是它没有上传到云 Firestore 数据库中

import 'package:firebase/firebase.dart' as fb;
import 'package:mime_type/mime_type.dart';
import 'package:path/path.dart' as p;

class ConstantFtns  {
  Future<Uri> uploadImageFile(
      MediaInfo mediaInfo, String ref, String fileName) async {
    try {
      String mimeType = mime(p.basename(mediaInfo.fileName));
       final String extension = extensionFromMime(mimeType);

      var metadata = fb.UploadMetadata(
        contentType: mimeType,
      );

      fb.StorageReference storageReference =
          fb.storage().ref(ref).child(fileName + ".$extension");

      fb.UploadTaskSnapshot uploadTaskSnapshot =
          await storageReference.put(mediaInfo.data, metadata).future;

      Uri imageUri = await uploadTaskSnapshot.ref.getDownloadURL();
      print("download url $imageUri");  <---- IT GETS P[RINTED AND IT SHOWED VALED IMAGE URL STORED IN STORAGE
      return imageUri;
    } catch (e) {
      print("File Upload Error $e");
      return null;
    }
  }
}

在此处输入图像描述

标签: imagefirebasefluttergoogle-cloud-firestoregoogle-cloud-storage

解决方案


由于您想要的只是将 URL 存储到 firestore 中,因此您并不需要将该getDownloadURL()值作为Uri对象,您只需要它的字符串值,即您收到转换错误的错误,我建议您遵循推荐的内容在这个社区答案中,您的代码将如下所示:

String uploadImageFile(
    MediaInfo mediaInfo, String ref, String fileName) async {
        try {
            ...

            var imageUri = await uploadTaskSnapshot.ref.getDownloadURL() as String;
            print("download url $imageUri");  <---- IT GETS P[RINTED AND IT SHOWED VALED IMAGE URL STORED IN STORAGE
            return imageUri
        } catch (e) {
            ...
        }
    }
})

而且您还必须将类中的调用更改ItemViewModel为:

String _uploadedImgURL = await ConstantFtns()
                 .uploadImageFile(pic, "ImgPathString", "fileName");

推荐阅读