Flutter Firestore Storage 获取 downloadUrl

Flutter Firestore Storage get downloadUrl

我需要下载URL 将照片上传到 Firebase 存储,这样我就可以将它存储在 Firestore 文档中。我的代码的问题是保存的 URL 不是 https//: 所以我需要下载 URL。我想知道我需要在哪里调用它来获取 downloadUrl 并将其保存在我的 Firestore 数据库中。

这是我的代码:

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

您可以在文件上传完成后随时对引用调用 getDownloadURL()。所以这将是一个好地方:

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