简体   繁体   中英

Handling null file from image_picker in image_cropper flutter?

I'm trying to get an image using image_picker package and then passing to image_cropper . I have taken a bit different approach to avoid getting back to the home screen after image selection before going to crop image screen.

Here is my code for image selection and image crop.

Future<File> getImageFromGallery(BuildContext context) async{
    final File croppedImage = await ImageCropper.cropImage(
        sourcePath: File((await ImagePicker().getImage(source: ImageSource.gallery)).path).path,
        maxWidth: 1080,
        maxHeight: 1080,
        aspectRatio: CropAspectRatio(ratioX: 1.0, ratioY: 1.0)
    );

    if (croppedImage  != null) {

      return croppedImage;
    }
    return null;
}
Error: The getter 'path' was called on null.

In tried Null Safety , but then it throws this error:

Failed assertion: line 81 pos 12: 'await File(sourcePath).exists()': is not true.

My code with Null Safety.

Future<File> getImageFromGallery(BuildContext context) async{

    final File croppedImage = await ImageCropper.cropImage(
        sourcePath: File((await ImagePicker().getImage(source: ImageSource.gallery)).path).path,
        maxWidth: 1080,
        maxHeight: 1080,
        aspectRatio: CropAspectRatio(ratioX: 1.0, ratioY: 1.0)
    );

    if (croppedImage  != null) {

      return croppedImage;
    }
    return null;
}

Please suggest me a better way to do what I'm trying to do.

var img = await ImagePicker().getImage(source: ImageSource.gallery);
final File croppedImage = await ImageCropper.cropImage(
    sourcePath: img.path,
    maxWidth: 1080,
    maxHeight: 1080,
    aspectRatio: CropAspectRatio(ratioX: 1.0, ratioY: 1.0)
);

I think you should pick up the img first, check if it's valid img or not. And then pass the path to imageCropper. So the code above should work fine..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM