gpt4 book ai didi

firebase - 无法将网址保存在Firestore中

转载 作者:行者123 更新时间:2023-12-03 04:21:34 25 4
gpt4 key购买 nike

我正在使用下面的代码将flutter应用程序中的选定图像上载到Firebase存储,这已成功完成,但是我无法将图片的url保存在firestore中,在这种情况下我在做什么错?

您可以在下面的代码中看到尝试存储URL的尝试。请指导我该如何纠正?

Future uploadFile(String uid) async {

StorageReference reference = FirebaseStorage.instance.ref().child('profile_pic/$uid');
StorageUploadTask uploadTask = reference.putFile(avatarImageFile);
StorageTaskSnapshot storageTaskSnapshot;
uploadTask.onComplete.then((value) {
if (value.error == null) {
storageTaskSnapshot = value;
storageTaskSnapshot.ref.getDownloadURL().then((downloadUrl) {
setState(() {
photoUrl = downloadUrl;

});
Firestore.instance
.collection('users')
.document(uid)
.setData({ 'photoUrl': photoUrl}).then((data) async {
setState(() {
isLoading = false;
});
Fluttertoast.showToast(msg: "Upload success");
}).catchError((err) {
setState(() {
isLoading = false;
});
Fluttertoast.showToast(msg: err.toString());
});
}, onError: (err) {
setState(() {
isLoading = false;
});
Fluttertoast.showToast(msg: 'This file is not an image');
});
} else {
setState(() {
isLoading = false;
});
Fluttertoast.showToast(msg: 'This file is not an image');
}
}, onError: (err) {
setState(() {
isLoading = false;
});
Fluttertoast.showToast(msg: err.toString());
});
}

最佳答案

该方法已经声明为异步方法,因此请尝试使用await而不是then():

Future uploadFile(String uid) async {

StorageReference reference = FirebaseStorage.instance.ref().child('profile_pic/$uid');
StorageTaskSnapshot snapshot = await reference.putFile(avatarImageFile).onComplete;
if (snapshot.error == null) {
final String photoUrl = await snapshot.ref.getDownloadURL();
Firestore.instance
.collection('users')
.document(uid)
.setData({ 'photoUrl': photoUrl}).then((data) async {
setState(() {
isLoading = false;
});
Fluttertoast.showToast(msg: "Upload success");
}).catchError((err) {
setState(() {
isLoading = false;
});
Fluttertoast.showToast(msg: err.toString());
});
}, onError: (err) {
setState(() {
isLoading = false;
});
Fluttertoast.showToast(msg: 'This file is not an image');
});
} else {
setState(() {
isLoading = false;
});
Fluttertoast.showToast(msg: 'This file is not an image');
}
}, onError: (err) {
setState(() {
isLoading = false;
});
Fluttertoast.showToast(msg: err.toString());
});
}

现在,当使用 await时,您将能够首先检索该URL,然后将其保存在Firestore中。

关于firebase - 无法将网址保存在Firestore中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62281968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com