Upload user profile picture Firebase - Flutter

Viewed 7083

I'm using ImagePicker to select a profile picture, once picture selected it'll be assigned to a Circle Avatar now how can I upload the picture into firebase. If the user refreshes the page(UI) Circle Avatar goes back to the default image! I need to replace the Circle Avatar with the currentUser's picture.

simply I don't know how to retrieve the image from firebase and assign it into Circle Avatar

Here's how I'm trying to update the 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

Uploading the picture -

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.");
}

This uploads the picture but I don't know how to retrieve this into Circle Avatar of that particular user's profile.

1 Answers

First you need to get the download URL of your stored photo:

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;
              });
    });

Then you can take the download URL store it in a variable and output it as you did in your code with Image.network(photoUrl).

Related