I am facing a weird problem that I haven't faced anywhere before, I am new to flutter and I am trying to upload images. the image uploads to the firebase storage but doesn't change inside the database. UNLESS I add a breakpoint to vscode, then it works both ways.
here is my code
Future<void> uploadCoverPic() async {
ImagePicker imagePicker = ImagePicker();
XFile? file = await imagePicker.pickImage(source: ImageSource.camera);
print('${file?.path}');
String uniqueFileName = DateTime.now().microsecondsSinceEpoch.toString();
Reference referenceDirImages = storageRef.child('usersCoverPics');
Reference refImagetoupload = referenceDirImages.child(uniqueFileName);
try {
refImagetoupload.putFile(File(file!.path));
_x = await refImagetoupload.getDownloadURL(); // I was adding a breakpoint here to see the value of _x but it solved my problem
UserModel user = UserModel(id: widget.user.id, coverImage: _x);
FirebaseServices.updateCoverPic(user);
} catch (error) {}
}
static void updateProfilePic(UserModel user) {
userRef.doc(user.id).update({'profilePicture': user.profilePicture});
}
what can I do to fix this?
CodePudding user response:
The putFile()
function is asynchronous, so your code is not waiting for a response from it before executing the code below. The reason why putting a breakpoint fixes your problem, is that you are pausing the execution of the code.
Read more about putFile()
on the official documentation.
To fix your code, add await
.
try {
await refImagetoupload.putFile(File(file!.path));
_x = await refImagetoupload.getDownloadURL();
UserModel user = UserModel(id: widget.user.id, coverImage: _x);
FirebaseServices.updateCoverPic(user);
} catch (error) {}
CodePudding user response:
Try to add await when you receive the response. Like this below
Future<void> uploadCoverPic() async {
ImagePicker imagePicker = ImagePicker();
XFile? file = await imagePicker.pickImage(source: ImageSource.camera);
print('${file?.path}');
String uniqueFileName = DateTime.now().microsecondsSinceEpoch.toString();
Reference referenceDirImages = storageRef.child('usersCoverPics');
Reference refImagetoupload = referenceDirImages.child(uniqueFileName);
try {
refImagetoupload.putFile(File(file!.path));
_x = await refImagetoupload.getDownloadURL(); // I was adding a breakpoint here to see the value of _x but it solved my problem
UserModel user = await UserModel(id: widget.user.id, coverImage: _x);
FirebaseServices.updateCoverPic(user);
} catch (error) {}
}