【问题标题】:Flutter uploading image to firebase storage then write it on firestoreFlutter将图像上传到firebase存储然后将其写入firestore
【发布时间】:2021-03-19 23:04:42
【问题描述】:

我正在制作一个程序,每当用户注册时,他们需要将图像上传到 firebase 存储,然后所有登录数据和图像 url 将在图像上传后立即写入 firestore,这是我的代码:

void signUp(String _email, String _password, File image) async {
  await _auth
      .createUserWithEmailAndPassword(email: _email, password: _password)
      .then((result) async{
    await uploadImage(image).then((value) {
      _firestore.collection('users').doc(result.user.uid).set({
      'uid': result.user.uid,
      'email': result.user.email,
      'imageUrl' : value!=null?value:""
    });
    });

Future<String> uploadImage(File image) async{
    String fileName = p.basename(image.path);
    Reference storageRef = _fstorage.ref().child('upload/$fileName');
    UploadTask uploadTask = storageRef.putFile(image);
    await uploadTask.whenComplete((){
      storageRef.getDownloadURL().then((imageUrl) { 
        return imageUrl!=null?imageUrl:"";
        });
    });
  }

问题是在firestore文档上写入的imageUrl的值总是空的,即使图像文件成功上传,任何建议都将不胜感激。谢谢

【问题讨论】:

  • 您是否尝试在上传后打印这些值?是返回网址吗?

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


【解决方案1】:

函数uploadImage 实际上并没有向调用者返回任何内容。您现在的 return 语句只是从传递给 whenComplete 的匿名函数返回一个值。它没有被传播到顶级函数之外。在编写之前尝试打印value 的值以查看它实际包含的内容。

您似乎只想简单地awaitputFilegetDownloadURL 的结果依次获取URL,然后返回它。

  Future<String> uploadImage(File image) async{
    String fileName = p.basename(image.path);
    Reference storageRef = _fstorage.ref().child('upload/$fileName');
    await storageRef.putFile(image);
    return await storageRef.getDownloadURL()
  }

我还建议查看documentation

【讨论】:

    【解决方案2】:
    Future<String> uploadItemImage(mFileImage) async {
        final Reference storageReference = 
           FirebaseStorage.instance.ref().child("Items");
      
        TaskSnapshot taskSnapshot = await 
          storageReference.child("product_$productId.jpg")
            .putFile(mFileImage);
        
        var downloadUrl = await taskSnapshot.ref.getDownloadURL();
    
        return downloadUrl;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-24
      • 2018-10-24
      • 2019-01-22
      • 1970-01-01
      • 2021-08-11
      • 2021-07-03
      • 2021-03-29
      • 2021-10-14
      相关资源
      最近更新 更多