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