簡體   English   中英

從另一個函數獲取圖像 - Flutter

[英]Getting image from another function - Flutter

我有兩個函數,它們是selectFile()uploadProduct() selectFile包含Image_PickerImage_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;
  }

split and.last 解釋

因此,如果imageData類似於app/name/image.jpg

imageData上調用split("/")會給出如下列表:

['app', 'name', 'image.jpg']

您可以將其視為“分隔”

然后, .last選擇列表中的最后一項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM