【问题标题】:How to save the Image to Firebase storage and save the URL to firebase firestore?如何将图像保存到 Firebase 存储并将 URL 保存到 Firebase Firestore?
【发布时间】:2021-03-14 09:46:02
【问题描述】:

您好,我正在尝试保存从图库或相机中挑选的图像。

Future<void> getImage({ImageSource source}) async {
    _pickedImage = await ImagePicker().getImage(source: source);
    if (_pickedImage != null) {
      _pickedImageFile = File(_pickedImage.path);
    }
  }

选择图像后,它必须将图像更新到 Firebase 存储。

void _uploadImage(File image) async {
    Reference storageReference = FirebaseStorage.instance
        .ref()
        .child('UserImage')
        .child("UserImage/${user.uid}");
    UploadTask uploadTask = storageReference.putFile(image);

    //StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    uploadTask.then((newUrl) async {
      newUrl.ref.getDownloadURL();
      return imageUrl = newUrl.toString();
    }).catchError((onError) {
      print(onError);
    });

  }

问题是代码在 uploadTask.then((newUrl) 处中断,并且不允许将 downloadURL 作为字符串获取。然后它必须将图像路径更新到 firestore 集合。

void userDetailsUpdate() {
    FirebaseFirestore.instance
        .collection("Manufacturer-Accounts")
        .doc(user.uid)
        .update({
      'Designation': designation.text,
      'FirstName': firstName.text,
      'LastName': lastName.text,
      //'Email': user.email,
      'Phone': phoneNumber.text,
      'UserImage': imageUrl == null ? "" : imageUrl,
    });
  }

因为它没有获取图像 url,所以将值保存为“”。有没有办法做到这一点?我使用了 Firebase 存储 ^5.0.1

我的完整源代码在这里How can I add a new value to my text editcontroller in Text formfield?

【问题讨论】:

  • 感谢克劳迪奥,但我已经尝试过这个,但对于 Firebase 存储的新更新,其中大多数已被弃用。谢谢你的时间

标签: flutter google-cloud-firestore firebase-storage imagepicker


【解决方案1】:

您的 _uploadImage 函数没有返回任何内容,因此调用它的人永远不会获得下载 URL。

Future<String> _uploadImage(File image) async {
    Reference storageReference = FirebaseStorage.instance
        .ref()
        .child('UserImage')
        .child("UserImage/${user.uid}");
    UploadTask uploadTask = storageReference.putFile(image);

    await Future.value(uploadTask);

    var newUrl = await storageReference.getDownloadURL();

    return newUrl;
}

现在您可以调用此函数并通过以下方式获取下载 URL:

var downloadURL = await _uploadImage(file);

【讨论】:

  • 感谢您帮助我。 Frank van Puffelen 感谢您的帮助
猜你喜欢
  • 2020-12-18
  • 2021-10-14
  • 2021-10-01
  • 2018-11-06
  • 2021-04-07
  • 2017-08-10
  • 2016-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多