上传图片到Firebase Storage报错:String类型不是Path类型的子类型
问题原因
你的报错是代码里两处问题共同导致的:
- Firebase Storage的
child()方法接收的参数是字符串类型的存储路径,你使用Path.from(_image.path)将原本是字符串的文件路径转为了Path类型对象,插值到字符串中时类型不匹配触发报错 - 存储路径的字符串模板末尾多写了一个多余的闭合大括号
},会导致最终生成的存储路径不符合预期
修复后的代码
Future uploadFile() async { // 直接用_image.path生成存储路径,删除多余的Path类型转换和冗余大括号 firebase_storage.Reference storageReference = FirebaseStorage.instance .ref() // 用split取最后一段文件名,避免把本地全路径同步到云端,不需要文件名可以直接写你的自定义规则 .child('chats/${_image.path.split('/').last}'); UploadTask uploadTask = storageReference.putFile(_image); await uploadTask; print('File Uploaded'); // 替换then回调为await写法,逻辑更清晰 String fileURL = await storageReference.getDownloadURL(); setState(() { print("UPLOADED FILE URL IS: ${fileURL}"); // _uploadedFileURL = fileURL; }); }
内容的提问来源于stack exchange,提问作者Kitcc
相关产品推荐
相关产品推荐

