gpt4 book ai didi

firebase - Flutter Firebase setData()函数在异步函数完成之前将空值分配给字段

转载 作者:行者123 更新时间:2023-12-03 02:59:53 28 4
gpt4 key购买 nike

我正在尝试为用户上载化身到Firestore存储并返回图像URL,以将其保存为用户实例上用户的avatarUrl属性。我可以将图片成功上传到Firestore。问题与URL的接收有关。异步函数会延迟,因此前面的用户实例化函数会使用avatarUrl属性的空值进行处理。
这是函数启动

                    if(_formKey.currentState.validate()){
setState(() {
loading=true;
});
await uploadFile();
print('Print before async function complete...');
print(_avatarUrl);
dynamic result= await SellerDatabaseService(uid:user.uid).sellerProfileSetup(
shopName: shopName,
phone: phone,
bio: bio,
location: location,
avatarUrl: _avatarUrl,
rating: 0,
sales: 0,
credit: 0,
posts: 0,
joinedDate:DateTime.now(),
//todo remove null from profile image
);
if(result==null){
setState(() {
loading=false;
error='Please supply correct details';
});
}
}
},
这是上传功能
 String _avatarUrl;
Future uploadFile() async {
StorageReference storageReference = FirebaseStorage.instance
.ref()
.child('avatars/${_image.path}');
StorageUploadTask uploadTask = storageReference.putFile(_image);
await uploadTask.onComplete;
print('File Uploaded');
storageReference.getDownloadURL().then((fileURL) {
setState(() {
_avatarUrl = fileURL;
print('Print after async function completes...');
print(_avatarUrl);

});
});
}
这是输出
I/flutter ( 7332): Print before async function complete...
I/flutter ( 7332): null
I/flutter ( 7332): Print after async function completes...
I/flutter ( 7332): https://firebasestorage.googleapis.com/v0/b/sakahapa-77a09.appspot.com/o/avatars%2Fdata%2Fuser%2F0%2Fcom.sakahapa.sakaHapa%2Fcache%2Fimage_picker246664303.jpg?alt=media&token=5868d6a5-b1e3-4aa2-8e64-72dc6e9b0a0f
如图所示,URL在 SellerDatabaseService(uid:user.uid).sellerProfileSetup()之后返回
功能已运行。所以我在avatarUrl属性上得到一个空值。我该如何预防?
提前致谢。

最佳答案

更改此:

    storageReference.getDownloadURL().then((fileURL) {
setState(() {
_avatarUrl = fileURL;
print('Print after async function completes...');
print(_avatarUrl);

});
});
到这个:
    var fileURL = await storageReference.getDownloadURL();
setState(() {
_avatarUrl = fileURL;
print('Print after async function completes...');
print(_avatarUrl);

});
});
使用 await而不是 then()。当前,您正在输入方法 uploadFile(),但是由于 getDownloadURL()是异步的,因此即使在获取URL之前, print()方法也会被执行。

关于firebase - Flutter Firebase setData()函数在异步函数完成之前将空值分配给字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62884198/

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