上传图片至Firebase Storage后无法立即获取下载链接的问题
问题原因及解决方案
你的代码存在两个核心问题,直接导致了“Object does not exist at location.”错误:
- 未等待上传完成就获取链接:
putData是异步操作,你调用后没有用await等待上传完成,此时Firebase Storage中的文件还未完全写入,自然无法获取到有效链接。 - 错误处理异步的下载链接:
getDownloadURL返回的是Future<String>类型,直接调用toString()得到的是Future对象的字符串标识,并非实际的下载链接,必须通过await获取真实结果。
修正后的代码如下:
late String img_url = ''; XFile? _pick; Future getImage() async { _pick = await _picker.pickImage(source: ImageSource.gallery); } Future uploadImage() async { if (_pick != null) { Uint8List _bytes = await _pick!.readAsBytes(); // 等待上传操作完成 await FirebaseStorage.instance.ref('/image/beta.jpg').putData(_bytes); // 通过await获取真实的下载链接 img_url = await FirebaseStorage.instance.ref('/image/beta.jpg').getDownloadURL(); print(img_url); // 现在能正常打印有效链接 } }
可以额外增加错误捕获逻辑,避免上传或获取链接失败导致程序崩溃:
Future uploadImage() async { if (_pick != null) { try { Uint8List _bytes = await _pick!.readAsBytes(); await FirebaseStorage.instance.ref('/image/beta.jpg').putData(_bytes); img_url = await FirebaseStorage.instance.ref('/image/beta.jpg').getDownloadURL(); print(img_url); } catch (e) { print('操作失败: $e'); } } }
内容的提问来源于stack exchange,提问作者qwerty970728
相关产品推荐
相关产品推荐

