我正在尝试将图像上传到Firebase存储并将该图像URL用作Firestore中的元数据,但是图像URL始终为null。这是代码
我如何获得图片
File noticepic;
Future getNotice()async{
var tempImage = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
noticepic=tempImage ;
});
}
我如何将其上传到Firebase存储
uploadNotice()async{
var randomno=Random(25);
final StorageReference firebaseStorageRef=FirebaseStorage.instance
.ref().child('cisnotices/${randomno.nextInt(5000).toString()}.jpg');
StorageUploadTask task = firebaseStorageRef.putFile(noticepic);
StorageTaskSnapshot snapshottask = await task.onComplete;
String downloadUrl = await snapshottask.ref.getDownloadURL();
noticeProvider.changePhotoUrl(downloadUrl.toString());
setState(() {
print('pic uploaded');
});
}
NoticeProvider noticeProvider=NoticeProvider();
这是noticeprovider.dart
changePhotoUrl(String value){
_photoUrl=value;
notifyListeners();
}
saveNotice(){
var newNotice=Notice(userName: userName,userPost: userPost,photoUrl: photoUrl,
date: date,noticeId: uuid.v4());
firestoreService.saveNotice(newNotice);
}
我如何通过按下图标按钮来触发拍照
child: IconButton(
icon: Icon(Icons.add_photo_alternate),
color: Colors.grey[700],
iconSize: 40,
onPressed:(){
getNotice().then((f) async => await uploadNotice());
}
),
答案 0 :(得分:1)
您可以使用此功能上传图片并从Firebase获取url
Future uploadFile(File file) async {
StorageReference storageReference = FirebaseStorage.instance.ref().child(
'${FirebaseStorageFolder.transactionDoc}/${Path.basename(file.path)}}');
StorageUploadTask uploadTask = storageReference.putFile(file);
var dowurl = await (await uploadTask.onComplete).ref.getDownloadURL();
print("done");
return dowurl.toString();
}