从另一功能获取图像-Flutter

pinkon5k  于 2022-12-24  发布在  Flutter
关注(0)|答案(1)|浏览(115)

我确实有两个函数,它们是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;
  }
zy1mlcev

zy1mlcev1#

既然你已经在类中有了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选取列表中的最后一项。

相关问题