[英]Firebase returns null photoUrl
I am building a mock social media app that allows users upload profile pictures to create their profiles.我正在构建一个模拟社交媒体应用程序,允许用户上传个人资料图片以创建他们的个人资料。 I am building this app in flutter. Right now, here's my uploadPic method:
我正在 flutter 中构建此应用程序。现在,这是我的 uploadPic 方法:
Future uploadPic(BuildContext context) async{
String fileName = basename(_image.path);
FirebaseStorage storage = FirebaseStorage.instance;
var photoUrl;
Reference ref = storage.ref().child(fileName);
var storedImage = File(_image.path);
UploadTask uploadTask = ref.putFile(storedImage);
uploadTask.then((res) {
photoUrl = res.ref.getDownloadURL();
});
print("photo url -- $photoUrl");
await widget.user?.updatePhotoURL(photoUrl);
await FirebaseAuth.instance.currentUser?.updatePhotoURL(photoUrl);
}
I have added the right permissions in my firebase console to allow read and write to the database.我在我的 firebase 控制台中添加了正确的权限以允许读取和写入数据库。 I know this because when I check firebase storage, I see the pictures have been uploaded successfully.
我知道这是因为当我检查 firebase 存储时,我看到图片已成功上传。 However, when I try to print the returned photo url (after the upload task completes), I get a null value.
但是,当我尝试打印返回的照片 url 时(上传任务完成后),我得到一个 null 值。 This is a problem when I try to access the photo in other areas in the app, because the user photoUrl in firebase is null.
当我尝试在应用程序的其他区域访问照片时,这是一个问题,因为 firebase 中的用户 photoUrl 是 null。
Is there anything I am doing wrong concerning the upload of the pic to firebase?关于将图片上传到 firebase,我做错了什么吗? Also, my terminal returns this: No App Check token for request.
此外,我的终端返回此信息:没有用于请求的 App Check 令牌。 .
. I'm wondering if this has anything to do with the issue?
我想知道这是否与问题有关?
Any help would be greatly appreciated!任何帮助将不胜感激!
your problem is simple, it's exactly from here:您的问题很简单,正是从这里开始:
var photoUrl;
uploadTask.then((res) {
photoUrl = res.ref.getDownloadURL();
});
print(photoUrl); // null
the problem is you are trying to print photoUrl
variable without waiting for the future uploadTask
to finish its work which results null
.问题是您正在尝试打印
photoUrl
变量而不等待未来的uploadTask
完成其结果null
的工作。
the solution is to wait for uploadTask
future before printing the photoUrl
variable:解决方案是在打印
photoUrl
变量之前等待uploadTask
future:
var photoUrl;
await uploadTask.then((res) async {
photoUrl = await res.ref.getDownloadURL();
});
print(photoUrl);
the solution on your code:您的代码的解决方案:
Future uploadPic(BuildContext context) async{
String fileName = basename(_image.path);
FirebaseStorage storage = FirebaseStorage.instance;
var photoUrl;
Reference ref = storage.ref().child(fileName);
var storedImage = File(_image.path);
UploadTask uploadTask = ref.putFile(storedImage);
await uploadTask.then((res) async {
photoUrl = await res.ref.getDownloadURL();
});
print("photo url -- $photoUrl");
await widget.user?.updatePhotoURL(photoUrl);
await FirebaseAuth.instance.currentUser?.updatePhotoURL(photoUrl);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.