首页 > 解决方案 > 上传用户个人资料图片 Firebase - Flutter

问题描述

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该特定用户的个人资料中。

标签: firebaseflutterdartfirebase-storage

解决方案


首先,您需要获取存储照片的下载 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) 一样输出它。


推荐阅读