如何将图像上传到Firebase存储并将图像URL保存到Firebase数据库以在flutter中使用它

时间:2020-03-03 19:21:01

标签: firebase flutter firebase-storage

我需要从Firebase存储中获取图像链接,并将其网址保存到Firestore字段中, 我有一个名为avatar(string)的字段,avatar值是firebase存储中的图像链接


  ClipRRect(
                                      child: Image.network(snapshot.data[index].data['avatar'],
                                        height: 100,
                                        width: 170,
                                        fit: BoxFit.fill,
                                      ),
                                      borderRadius: BorderRadius.circular(20),
                                    ),

和错误代码

════════ Exception caught by image resource service ════════════════════════════════════════════════
The following ArgumentError was thrown resolving an image codec:
Invalid argument(s): Unsupported scheme 'gs' in URI gs://pfe-2020-51d9c.appspot.com/Ail/14118b537d_100727_bienfaits-ail.jpg

When the exception was thrown, this was the stack: 
#0      _HttpClient._openUrl (dart:_http/http_impl.dart:2278:9)
#1      _HttpClient.getUrl (dart:_http/http_impl.dart:2197:48)
#2      NetworkImage._loadAsync (package:flutter/src/painting/_network_image_io.dart:84:59)
#3      NetworkImage.load (package:flutter/src/painting/_network_image_io.dart:47:14)
#4      ImageProvider.resolve.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:flutter/src/painting/image_provider.dart:327:17)
...
Image provider: NetworkImage("gs://pfe-2020-51d9c.appspot.com/Ail/14118b537d_100727_bienfaits-ail.jpg", scale: 1.0)
Image key: NetworkImage("gs://pfe-2020-51d9c.appspot.com/Ail/14118b537d_100727_bienfaits-ail.jpg", scale: 1.0)

═══════════════════════════════════════════════ ══════════════════════════════════

1 个答案:

答案 0 :(得分:0)

1)创建文件变量以保存图像:

您可以使用image_picker从手机中选择图片。

File file;

2)创建选择图像的功能

handleChooseImageFromGallery() async {
File _file = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
  this.file = _file;
});
}

如果要使用手机摄像头拍摄图像,可以在中传递 ImageSource.camera

3)将图像上传到Firebase存储

Future<String> handleUploadImage(imageFile) async {
// Upload imageFile to firebase storage
// TODO: use uuid for pictureId

StorageUploadTask uploadTask =
    storageRef.child("${user.id}_profilePic_$picId.jpg").putFile(imageFile);
StorageTaskSnapshot storageTaskSnapshot = await uploadTask.onComplete;
// Once the image is uploaded to firebase get the download link.
String downlaodUrl = await storageTaskSnapshot.ref.getDownloadURL();
return downlaodUrl;
}

此函数将返回图像网址。

4)将图像网址保存在Firestore文档中

void handleUpdateUserProfile()
{
    String mediaUrl = await handleUploadImage(file); // Pass your file variable 
    // Create/Update firesotre document
    usersRef.document(userId).updateData(
    {
        "avatar": mediaUrl,
    }
    );
}