Ad

Flutter Firestore Storage Get DownloadUrl

I need to get the downloadURL from uplaoding a photo to a Firebase Storage so I can store it inside of a Firestore document. The issue with my code is that the URL that is saved isnt a https//: so I need to get the downloadURL. I was wondering where I need to call it to get the downloadUrl and save it inside of my Firestore Database.

Here is my code:

  Future<void> _uploadProfilePhoto(String inputSource) async {
    final picker = ImagePicker();
    PickedFile? pickedImage;
    try {
      pickedImage = await picker.getImage(
          source: inputSource == 'camera'
              ? ImageSource.camera
              : ImageSource.gallery,
          maxWidth: 1920);

      final String fileName = path.basename(pickedImage!.path);
      File imageFile = File(pickedImage.path);

      try {
        await storage.ref("avatars/$fileName").putFile(
            imageFile,
            SettableMetadata(customMetadata: {
              'uploaded_by': '$uid',
            }));
            
        // Create/Update firesotre document
        users.doc(uid).update({
          "profilePhoto": fileName,
        });

        setState(() {});
      } on FirebaseException catch (error) {
        print(error);
      }
    } catch (err) {
      print(err);
    }
  }
Ad

Answer

You can call getDownloadURL() on the reference at any time after the file upload has completed. So this would be a good spot:

await storage.ref("avatars/$fileName").putFile(
    imageFile,
    SettableMetadata(customMetadata: {
      'uploaded_by': '$uid',
    }));
var downloadURL = await storage.ref("avatars/$fileName").getDownloadURL();       
// Create/Update firesotre document
users.doc(uid).update({
  "profilePhoto": downloadURL,
});
Ad
source: stackoverflow.com
Ad