将用户个人资料图片上传至Firebase - Flutter

3
我正在使用ImagePicker来选择个人资料图片,一旦选择了图片,它将被赋值给Circle Avatar,现在我该如何将这张图片上传到Firebase中。如果用户刷新页面(UI),Circle Avatar又回到了默认的图片!我需要用当前用户的图片替换Circle Avatar
简单来说,我不知道如何从Firebase检索图片并将其分配到Circle Avatar中。
以下是我尝试更新圆形头像的方式 -
 CircleAvatar(
                            radius: 30.0,
                            backgroundColor: Colors.white,
                            child: (_imageFile != null)
                                ? Container(
                                    decoration: BoxDecoration(
                                      shape: BoxShape.circle,
                                      image: DecorationImage(
                                          image: FileImage(_imageFile),//Selected Image
                                          fit: BoxFit.fill),
                                    ),
                                  )
                                : Image.network(
                                    (photoUrl == null)
                                        ? 'https://www.materialui.co/materialIcons/image/add_a_photo_black_36x36.png'//Default Picture
                                        : photoUrl,
                                    fit: BoxFit.fill,
                                  ), //Replace with Image From DB

上传图片 -

Future UpdatePic() async{
   String fileName = basename(_imageFile.path);
  StorageReference firebaseStorageRef =
      FirebaseStorage.instance.ref().child(fileName);
  StorageUploadTask uploadTask = firebaseStorageRef.putFile(_imageFile);
  StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
  showInSnackBar("Picture updated successfully.");
}

这会上传图片,但我不知道如何将其检索到特定用户配置文件的 Circle Avatar 中。

你能给我展示一个例子吗?我是Flutter的新手,不知道怎么做。 - Pranav
我正在查看你的代码。除了显示文件图像的奇怪方式之外,我没有发现任何问题。 - Christopher Moore
请告诉我如何从Firebase中获取文件引用,并将其用于“Circle Avatar”(引用需要是currentUser的文件)。 - Pranav
你已经在本地拥有文件引用了。它是 _imageFile。这是你正在上传的同一个文件。如果你已经拥有该文件,就没有必要浪费资源从存储中读取。 - Christopher Moore
你应该在问题中澄清这一点。你尝试从存储中检索图像了吗?有很多文档可供参考。 - Christopher Moore
显示剩余4条评论
1个回答

0

首先,您需要获取存储照片的下载URL:

FirebaseStorage.instance
          .ref() //if your photos are inside another folder, lets say avatarPhotos
                 // you need to put that here also to get the download URL, with
                 // another .child('avatarPhotos') 
          .child(fileName)
          .getDownloadURL()
          .then((value) => {
                 //here you can either set your photoUrl to value or assuming
                 //assuming you have a database with users with profile pictures, 
                 //you can call a method to update the user with this value
                 photoUrl = value;
              });
    });

然后,您可以将下载URL存储在变量中,并像您在代码中使用Image.network(photoUrl)一样输出它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接