Flutter上传图片到Firebase Storage提示StorageUploadTask无future getter错误
报错原因
这个报错是因为你使用的firebase_storage包版本高于1.0.0,该版本对API做了破坏性变更:
- 原
StorageUploadTask类已重命名为UploadTask - 移除了
UploadTask的future属性,UploadTask本身已经实现了Future接口,可直接等待执行完成 - 原
StorageReference类重命名为Reference - 上传完成后不能直接从任务返回值获取
downloadUrl,需要通过存储引用单独调用getDownloadURL()方法获取
修复后的代码
class _SelectprofilepicPageState extends State<SelectprofilepicPage> { File? newProfilePic; // 未开启空安全可去掉? Future getImage() async { // 若使用image_picker 0.8.x以下旧版本,可保留ImagePicker.pickImage写法,无需转XFile var tempImage = await ImagePicker().pickImage(source: ImageSource.gallery); setState(() { if (tempImage != null) { newProfilePic = File(tempImage.path); } }); } Future uploadImage() async { if (newProfilePic == null) return; // 原写法Random(25)用了固定种子,会生成重复随机数导致文件覆盖,此处改为无参数随机 var randomno = Random(); final Reference firebaseStorageRef = FirebaseStorage.instance .ref() .child('profilepics/${randomno.nextInt(5000).toString()}.jpg'); UploadTask task = firebaseStorageRef.putFile(newProfilePic!); // 未开启空安全可去掉! // 直接await任务完成,不需要调用.future await task.whenComplete(() async { String downloadUrl = await firebaseStorageRef.getDownloadURL(); userManagement.updateProfilePicture(downloadUrl).then((val) { //Navigator.of(context).pushReplacementNamed('/homepage'); }); }).catchError((e) { print(e); }); } }
其他可选方案
如果你不想适配新版API,可以将pubspec.yaml中firebase_storage的版本降级到^0.8.0+1,原有代码无需修改即可运行,但更推荐适配新版API避免后续兼容问题。
内容的提问来源于stack exchange,提问作者b s
相关产品推荐
相关产品推荐

