How to rebuild profile picture widget on changes to file in Firebase Storage (Flutter)

Viewed 773

I am trying to build a profile picture widget in Flutter that allows the user to upload an image to Firebase storage and retrieve that image once it has been uploaded. My problem is that I call the _getImage() Function in initState() so anytime the user uploads a new photo the widget isn't rebuilt with the new photo unless the app is restarted. Is there a 'stream' like method I can use to listen to changes in a Firebase Storage location and rebuild a widget accordingly?

I use ImagePicker to get my image from gallery.

_pickImage() async {
final selected = await ImagePicker().getImage(source: ImageSource.gallery);
setState(() {
  _imageFile = File(selected.path);
});
_uploadFile(_imageFile);}

After the photo is chosen, it is uploaded to Firebase Storage.

_uploadFile(File _imageFile) async{
  var user = await FirebaseAuth.instance.currentUser();
  var storageRef = _storage.ref().child('user/profile/${user.uid}');
  var uploadTask = storageRef.putFile(_imageFile);
}

Then to retrieve the image, I call the _getImage() function in initState().

void initState() {
  super.initState();
  _getImage();

}

the _getImage() funtion.

_getImage() async {
var user  = await FirebaseAuth.instance.currentUser();
var photoReference = _storage.ref().child("user/profile/${user.uid}");
photoReference.getData(1000000000).then((data){
  this.setState(() {
    imageFile = data;
  });
}).catchError((onError){
  print('error');
}); }
1 Answers

here is a example

final image = await ImagePicker()
                  

.pickImage(source:  ImageSource.gallery);

                  if (image == null) return;
              FirebaseStorage storage = FirebaseStorage.instance;
              Reference ref = storage.ref().child("images/${DateTime.now()}");
              UploadTask uploadTask = ref.putFile(File(image.path));
              uploadTask.then((res) async {
              String fileurl = await (await uploadTask).ref.getDownloadURL();
              return fileurl;

You have to upload image on firebase then retrieve the image url then you can call it on user profile

Related