[英]Getting image from another function - Flutter
我有兩個函數,它們是selectFile()
和uploadProduct()
。 selectFile
包含Image_Picker
和Image_Cropper
。 現在我需要從我的uploadProduct()
中的selectFile
獲取路徑和文件,以將其上傳到我的 Firebase 存儲並將 URL 存儲在我的 firestore 中,我不知道如何傳遞它。
PlatformFile? pickedFile;
UploadTask? uploadTask;
String imagePath = "";
Future selectFile() async {
try {
final image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image != null) {
final croppedImage = await ImageCropper().cropImage(
sourcePath: image!.path,
aspectRatio: const CropAspectRatio(ratioX: 1, ratioY: 1),
compressQuality: 100,
maxWidth: 450,
maxHeight: 450,
compressFormat: ImageCompressFormat.jpg,
aspectRatioPresets: [CropAspectRatioPreset.square],
);
setState(() {
imagePath = croppedImage!.path;
});
}
} on PlatformException catch (e) {
print(e);
Navigator.of(context).pop();
}
}
Future uploadProduct() async {
// i should be passing here the path
final path = 'products/${pickedFile!.name}';
// I should be passing here the file
final file = File(croppedImage!.path);
final ref = FirebaseStorage.instance.ref().child(path);
uploadTask = ref.putFile(file);
final snapshot = await uploadTask!.whenComplete(() {});
final urlDownload = await snapshot.ref.getDownloadURL();
var url = urlDownload.toString();
// I haven't started the storing of the url to firestore since i can't upload the file on firestore storage.
print(url);
return url;
}
因為你已經在課堂上有了imagePath
,我想,你可以試試這個:
Future uploadProduct() async {
final path = 'products/${imagePath.split("/").last}';
final file = File(imagePath);
final ref = FirebaseStorage.instance.ref().child(path);
uploadTask = ref.putFile(file);
final snapshot = await uploadTask!.whenComplete(() {});
final urlDownload = await snapshot.ref.getDownloadURL();
var url = urlDownload.toString();
print(url);
return url;
}
因此,如果imageData
類似於app/name/image.jpg
在imageData
上調用split("/")
會給出如下列表:
['app', 'name', 'image.jpg']
您可以將其視為“分隔”
然后, .last
選擇列表中的最后一項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.